[英]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: 在解析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.