gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:52:00 24 4
gpt4 key购买 nike

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

在上面的代码片段中我只想要 key 。我正在通过对象属性迭代一个变量,它只给我“类型”和“属性”。但我想要嵌套对象中存在的所有键。递归是解决这个问题的唯一方法。但未能将逻辑应用到上面的代码片段中。我如何识别特定键的值又是一个对象..??

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

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

最佳答案

您可以使用reviver JSON.parse 的回调,用于在解析 json 字符串时收集 key :

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

关于javascript - 需要仅提取 JSON 模式中存在的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42840351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com