JavaScript 解析带有动态变量的嵌套 JSON

javascript parse nested json with dynamic variable

本文关键字:变量 嵌套 JSON 动态 JavaScript      更新时间:2023-09-26

我正在尝试解析由api调用返回的一些嵌套json。以下是所返回内容的简化版本。

{
  "Includes":{
    "Products":{
      "P123456":{
        "Brand":{},
        "Description":"ipsem lorem",
        "Statistics":
          [
           "Author":"John Smith",
           "IsFeatured":false,
           "Total": 3
          ]
       }
     }
   }
 }

我尝试了几种不同的语法来获得我需要的东西,其中 product_code = "P123456"

data.Includes.Products.product_code.Statistics
data.Includes.Products[product_code].Statistics

我也尝试使用"get"和"eval"无济于事。错误响应始终相同

application.js:1639 Uncaught TypeError: Cannot read property 'Statistics' of undefined

我知道产品代码是正确的,因为我已经控制台记录了它。我也成功地控制台登录

data.Includes.Products["P123456"].Statistics

如何访问嵌套在产品代码"P123456"下的数据?该项目使用zepto而不是jQuery。

Object.keys(data.Includes.Products)将在产品下返回一个键数组。

如果你想要第一个Object.keys(data.Includes.Products)[0].

可以检索统计信息

var key = Object.keys(data.Includes.Products);
var statistics = data.Includes.Products[key].Statistics;

纯JavaScript ...没有库。

附言。您的 JSON 格式不正确。那个"统计"数组会引起眼泪。

使用有效的数据结构,您可以通过以下方式访问它

object.Includes.Products.P123456

object.Includes.Products[product_code]

var object = {
        "Includes": {
            "Products": {
                "P123456": {
                    "Brand": {},
                    "Description": "ipsem lorem",
                    "Statistics": { // its an object, not an array
                        "Author": "John Smith",
                        "IsFeatured": false,
                        "Total": 3
                    }
                }
            }
        }
    },
    product_code = 'P123456';
document.write('<pre>' + JSON.stringify(object.Includes.Products.P123456, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(object.Includes.Products[product_code], 0, 4) + '</pre>');

你已经试过了吗? data.Includes.Products.P123456.Statistics ?它看起来像属性,而不是索引字符串。