如何将解析后的JSON键值分别存入变量并整理为指定格式?
Solution to Collect Keys and Values from JSON
Let's adjust your existing code to gather the keys and values into the two specific arrays you need. Here's a straightforward implementation:
// Parse the incoming JSON data var json = $.parseJSON(data); // Initialize empty arrays to store our desired collections var monthYearStrings = []; var numericValues = []; // Loop through each top-level item in the parsed JSON $(json).each(function(i, val) { // Iterate over each key-value pair in the current item $.each(val, function(k, v) { // Add the key (like "JAN_2018") to our string array monthYearStrings.push(k); // Add the value (converted to a number) to our numeric array numericValues.push(Number(v)); // Use parseInt(v, 10) instead if you strictly need integer values }); }); // Verify the results (optional) console.log("Formatted strings:", monthYearStrings); console.log("Numeric values:", numericValues);
Key Details:
- We declare the two arrays outside the loops so they keep their data across all iterations.
- Using
push()adds each key and value to their respective arrays as we loop through the JSON. - The
Number(v)conversion ensures that even if the JSON returns values as strings, they get converted to numeric type. If you’re certain the values are already numbers in the JSON, you can just pushvdirectly.
Example Scenario:
If your input JSON looks like this:
[ {"JAN_2018": 1081136328}, {"FEB_2018": 1069248328}, {"MAR_2018": 1075621340} ]
Your final arrays will be:
monthYearStrings = ["JAN_2018", "FEB_2018", "MAR_2018"]numericValues = [1081136328, 1069248328, 1075621340]
This should give you exactly the format you’re looking for. Let me know if you need adjustments based on your specific JSON structure!
内容的提问来源于stack exchange,提问作者user9644415
相关产品推荐
相关产品推荐

