简体   繁体   English

遍历 typescript 中的嵌套 JSON 字符串

[英]Iterating over nested JSON string in typescript

I have a test nested JSON string.我有一个测试嵌套的 JSON 字符串。

const testString = `{
  "object1": {
    "5": [
      {
        "id": "A2OKPZ5S9F78PD",
        "rate": "2",
        "item": "item",
        "status": "status"
      }
    ]
  },
  "type": "LIVE_EVENT"
}`;

const model = JSON.parse(testString);
Object.values(model.object1).forEach((obj) =>
  obj.foreach((innerObj) => console.log(innerObj))
);

As you can see above I am trying to parse this as JSON and iterate over.正如您在上面看到的,我试图将其解析为 JSON 并迭代。 The problem which I am facing during JSON.parse the inner object assumes the type undefined and foreach can not be applied on it.我在 JSON.parse 内部 object 期间遇到的问题假定类型为 undefined 并且 foreach 不能应用于它。 Can some one please help?有人可以帮忙吗?

Your JSON is was invalid (before an edit) due to an extra comma after the status key/value pair and forEach() has an uppercase E. Also, as discussed in the comments below it seems you need to cast the inner obj to be of a type that understands forEach() :JSON 无效(在编辑之前),因为在状态键/值对和forEach()有一个大写 E 之后有一个额外的逗号。此外,正如在下面的评论中所讨论的,您似乎需要将内部obj转换为理解forEach()的类型:

 const testString = `{"object1":{"5":[{"id":"A2OKPZ5S9F78PD","rate":"2","item":"item","status":"status"}]},"type":"LIVE_EVENT"}`; const model = JSON.parse(testString); Object.values(model.object1).forEach((obj) => (obj as any).forEach((innerObj) => console.log(innerObj)) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM