简体   繁体   English

使用 JSON 模式或类解析嵌套的 JSON

[英]Parsing nested JSON using JSON Schema or Classes

I have a large nested JSON response in following sample format:我有以下示例格式的大型嵌套 JSON 响应:

{
  "type": "folder",
  "path": "Path1",
  "owner": "user1",
  "entries": [{
    "type": "folder",
    "path": "Path2",
    "owner": "user1",
    "entries": [{
        "type": "folder",
        "path": "Path3",
        "owner": "user1"
      },
      {
        "type": "file",
        "path": "FullFilePath1",
        "owner": "user1"
      }
    ]
  }]
}

I wanted to extract all the file type with selected keys and also add additional keys:我想用选定的键提取所有文件类型并添加其他键:

{
  "type": "file",
  "path": "FullFilePath1",
  "Application": "My Application",
  "UpdatedTime": "Time"
}

I am using nodejs.我正在使用nodejs。 I need inputs in parsing the JSON file in best way.我需要以最佳方式解析 JSON 文件的输入。 I was trying to check if I can use JSON Schema and Classes to do this but still didnt get through.我试图检查是否可以使用 JSON 模式和类来执行此操作,但仍然没有通过。

Could you please guide me?你能指导我吗?

Since you are dealing with JSON, you can simply load it into a JavaScript variable using require:由于您正在处理 JSON,因此您可以使用 require 将其简单地加载到 JavaScript 变量中:

let data = require('./data.json');

You can then loop the variable for all entries tag然后,您可以为所有条目标签循环变量

let fileData = require('./data.json');
let allEntries = [];
loadEntries(fileData);
function loadEntries(data) {
    if(data.entries) {
        for (let index = 0; index < data.entries.length; index++) {
            const entry = data.entries[index];
            // Do something with the entry
            allEntries.push(entry);
            loadEntries(entry);
        }
    }
}

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

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