简体   繁体   中英

Need to Extract only keys present in the JSON schema

  {
    "type" : "object",
    "properties" : {
       "header" : {
         "type" : "object",
         "properties" : {
            "outType" : {
              "type" : "string"
            },
            "id" : {
              "type" : "string"
            },
            "application" : {
              "type" : "string"
            },
            "userId" : {
              "type" : "string"
            },
         }
       }
    }

In the above snippet i only want the keys. I am iterating a variable through the object properties which is giving me only "type" & "properties". But I want all the keys present in nested objects. Recursion is the only solution to this. But failing in applying the logic to the above snippet. How can I identify that the value of a particular key is again an object..??

I am try it with this above function, is that correct?

function traverse(myObj) {
  for (x in myObj) {
    if typeof myObj[x] == 'string'
    then print(x);
    else traverse(myObj[x])
  }
}

You could use reviver callback of JSON.parse to collect the keys at the time when you parse your json string:

 var keys = []; var json = '{"type":"object","properties":{"header":{"type":"object","properties":{"outType":{"type":"string"},"id":{"type":"string"},"application":{"type":"string"},"userId":{"type":"string"}}}}}'; var data = JSON.parse(json, function(key, value) { // if the key exists and if it is not in the list then add it to the array if (key // && typeof value === 'object' //only required if you only want the key if the value is an object && keys.indexOf(key) === -1) { keys.push(key); } //return the original value so that the object will be correctly created return value; }); console.log(keys); console.dir(data); 

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