[英]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"
},
}
}
}
在上面的代码片段中,我只想要密钥。 我通过对象属性迭代一个变量,它只给我“类型”和“属性”。 但我希望嵌套对象中存在所有键。 递归是唯一的解决方案。 但未能将逻辑应用于上述代码段。 如何识别特定键的值又是一个对象.. ??
我试试这个上面的功能,这是正确的吗?
function traverse(myObj) {
for (x in myObj) {
if typeof myObj[x] == 'string'
then print(x);
else traverse(myObj[x])
}
}
在解析json字符串时,可以使用JSON.parse
reviver
回调来收集键:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.