You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将解析后的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 push v directly.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:17:34