使用JavaScript从纯文本过滤并生成指定JSON数组
Extract Target JSON Array from Plain Text using JavaScript
Here's a practical, step-by-step solution to parse your plain text input into the exact JSON structure you need:
Step 1: Break Down the Input Structure
Your input has two lines of trade data. Each line starts with an index, followed by a variable-length name segment, a shortform identifier, then a series of numeric values. We need to pull three key fields:
traded: The unique shortform (likeshortform1orshortform2)close: The 4th numeric value immediately after the shortformpreviousClose: As specified in your target output, we'll use355(adjust this logic later if you need to pull it from a specific position in the input)
Step 2: JavaScript Code Implementation
const inputText = `1 agri dev ban lt shortform1 346 346 343 343 9,671 346 3,330,659 78 -3.00 -0.87 3.00 0.87 361.80 400.07 449.86 472.00 283.00 2 Api Pwr Cpy shortform2 355 355 347 348 2,702 355 942,793 36 -7.00 -1.97 8.00 2.31 366.09 465.42 479.63 683.00 246.00`; // Split input into individual lines, ignoring any empty lines const lines = inputText.split('\n').filter(line => line.trim() !== ''); // Process each line to extract the required fields const parsedData = lines.map(line => { // Split the line into parts, handling multiple spaces between elements const parts = line.split(/\s+/); // Find the shortform: it's the last non-numeric part before the first numeric value (after the initial index) let shortformIndex = -1; for (let i = 1; i < parts.length; i++) { if (!isNaN(parseFloat(parts[i])) && parts[i].trim() !== '') { shortformIndex = i - 1; break; } } const traded = parts[shortformIndex]; // Extract the close value: 4th numeric entry after the shortform (strip commas from formatted numbers first) const closeValue = parseFloat(parts[shortformIndex + 4].replace(/,/g, '')); // Set previousClose (matches your target output; adjust if this needs to come from the input) const previousClose = 355; return { traded, close: closeValue, previousClose }; }); // Convert the parsed data to a formatted JSON string const resultJSON = JSON.stringify(parsedData, null, 2); console.log(resultJSON);
Step 3: Expected Output
Running this code will log the following JSON array to your console:
[ { "traded": "shortform1", "close": 343, "previousClose": 355 }, { "traded": "shortform2", "close": 348, "previousClose": 355 } ]
Quick Adjustments
- If
previousCloseshould be pulled from a specific position in your input (instead of being hardcoded), replaceconst previousClose = 355;with something likeconst previousClose = parseFloat(parts[shortformIndex + 1].replace(/,/g, ''));(to use the first numeric value after the shortform). - The code automatically handles numeric values with commas (like
9,671) by stripping commas before parsing to a number. - The shortform detection works even if the name segment has a variable number of words (4 words in the first line, 3 in the second).
内容的提问来源于stack exchange,提问作者samcro
相关产品推荐
相关产品推荐

