需要仅提取JSON模式中存在的键

时间:2017-03-16 16:58:48

标签: javascript json

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

在上面的代码片段中我只想要密钥。我通过对象属性迭代一个变量,它只给我“类型”& “属性”。但我希望嵌套对象中存在所有键。递归是唯一的解决方案。但未能将逻辑应用于上述代码段。 如何识别特定键的值又是一个对象.. ??

我尝试使用上面这个函数,这是正确的吗?

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

1 个答案:

答案 0 :(得分:0)

您可以使用reviver回调JSON.parse来收集解析json字符串时的键:

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