简体   繁体   中英

Parsing nested JSON using JSON Schema or Classes

I have a large nested JSON response in following sample format:

{
  "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. I need inputs in parsing the JSON file in best way. I was trying to check if I can use JSON Schema and Classes to do this but still didnt get through.

Could you please guide me?

Since you are dealing with JSON, you can simply load it into a JavaScript variable using require:

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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