简体   繁体   English

解析多级 JSON Output Javascript

[英]Parsing Multi-Level JSON Output Javascript

EDITED WITH UPDATED OUTPUT I was able to use the request module which now provides me with verified standard JSON output.使用更新的 OUTPUT进行编辑我能够使用请求模块,该模块现在为我提供了经过验证的标准 JSON output。 See below output:见下文 output:

 const respBody = { "items": [ { "id": "T0lDX0J1aWxkX0FydGlmYWN0czpmODk4YjM5MDNjYjk5YzU5NjgzNTk3ZWRjNWFmZjliYw", "repository": "Build_Artifacts", "format": "raw", "group": "/", "name": "myFile.zip", "version": null, "assets": [ { "downloadUrl": "http://localhost:8081/repository/Build_Artifacts/myFile.zip", "path": "myFile.zip", "id": "T0lDX0J1aWxkX0FydGlmYWN0czphNDc1N2JjYWE2MmI2MzA2MDdlMTA1NGE4NTk1MDQ1OQ", "repository": "OIC_Build_Artifacts", "format": "raw", "checksum": { "sha1": "040e517528c05ca335a38e98c7ab8673773314bd", "sha512": "652e624873da778dce4bc417cacfead12bdd2ad01e9f7f77cba80270caa0f99caa09d4fb53f584a4da9991186f78bd7b55da1e4ed3f22e026b8333dd332b3b83", "sha256": "b66805d15702505f708b90f6e1169c79390d59b9f8cadc9ab1852f48eeabbfe2", "md5": "60fdd406e026330c2cfbec3e15e05414" } } ] }] }

I was able to parse what I needed with "respbody.items[0].name"我能够用“respbody.items[0].name”解析我需要的东西

That isn't the JSON standard covered by JSON.parse() .那不是JSON.parse()涵盖的 JSON 标准。 The easiest way to get the object would be to use eval() :获得 object 的最简单方法是使用eval()

let array = global
  .eval("[{foo: 'bar', name: 'value'}]")
  .map(item => {
    return {name: item.name};
  });

// will output: [{name: "value"}]
console.log(array);

But that would be totally unsave, like MDN writes:但这将完全无法挽救,就像 MDN 写道:

Warning: Executing JavaScript from a string is an enormous security risk.警告:从字符串执行 JavaScript 是一个巨大的安全风险。 It is far too easy for a bad actor to run arbitrary code when you use eval() .当您使用eval()时,坏演员很容易运行任意代码。 See Never use eval()!请参阅从不使用 eval()! , below. , 以下。

A better way would be using JSON5 , which also supports the object notation of ES5 JavaScript.更好的方法是使用JSON5 ,它还支持 ES5 JavaScript 的 object 表示法。 It is also available over npm:它也可通过 npm 获得:

https://www.npmjs.com/package/json5 https://www.npmjs.com/package/json5

For more information about that see the question " Parsing "relaxed" JSON without eval ".有关这方面的更多信息,请参阅问题“ Parsing "relaxed" JSON without eval ”。

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

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