出于无法控制的原因,我需要在具有不同结构的JSON中搜索相同的键值。
我的代码能够找到“ valor”的值,并且无论JSON的结构是什么,在其中始终都会有一个供应商密钥。
现在我有两个接收到的JSON示例:
[2,"4:4","ExtraNotification",{"typeModel":"553","serialNumber":"0218-009","vendor":"ABC","version":"4.0.2.14"}]
和
{"id":"101010c90310","timestamp":"2019-02-18T18:33:35.819925957Z","station":true,"type":"call","action":"ExtraNotification","payload":{"model":"F254A","serialNumber":"1543906","vendor":"EVZ","version":"0.180601","si":"2048188","icid":"89312490184"}}
我尝试将其映射,以检查该属性是否未定义,没有任何作用。
答案 0 :(得分:1)
您可以通过键搜索对象或数组。如果找到了您要查找的密钥,请返回它。否则,递归地将沿途找到的所有对象传递回去:
let j = [2,"4:4","ExtraNotification",{"typeModel":"553","serialNumber":"0218-009","vendor":"ABC","version":"4.0.2.14"}]
let j2 = {"id":"101010c90310","timestamp":"2019-02-18T18:33:35.819925957Z","station":true,"type":"call","action":"ExtraNotification","payload":{"model":"F254A","serialNumber":"1543906","vendor":"EVZ","version":"0.180601","si":"2048188","icid":"89312490184"}}
function findKey(obj, key) {
for ([k, v] of Object.entries(obj)){
if (k == key) return v
if (typeof v === 'object' && v !== null ){
let found = findKey(v, key)
if (found) return found
}
}
}
console.log(findKey(j, 'vendor'))
console.log(findKey(j2, 'vendor'))
这类似于find()
,并返回通过深度优先搜索找到的第一个匹配项。
答案 1 :(得分:1)
我写了一小段递归代码。它适用于以下输入:
var input = [2,"4:4","ExtraNotification",{"typeModel":"553","serialNumber":"0218-009","vendor":"ABC","version":"4.0.2.14"}, [{ "vendor": "111"}, { "vendor": "222"} ]];
//var input = {"id":"101010c90310", "test": { "test1": { "vendor": "aaa" } }, "timestamp":"2019-02-18T18:33:35.819925957Z","station":true,"type":"call","action":"ExtraNotification","payload":{"model":"F254A","serialNumber":"1543906","vendor":"EVZ","version":"0.180601","si":"2048188","icid":"89312490184"}};
var founds = [];
function search(obj) {
if (obj instanceof Array) {
for(var i = 0; i < obj.length; i++) {
search(obj[i]);
}
} else {
for(var key in obj) {
if (key == "vendor") {
founds.push(obj[key]);
} else if (typeof obj[key] == "object") {
search(obj[key]);
}
}
}
};
search(input);
console.log(founds);
// First input: ["ABC", "111", "222"]
// Second input: ["aaa", "EVZ"]
答案 2 :(得分:-1)
您可以跳过parse
(或返回stringify
)并在字符串中搜索。没有什么应该发生...
const json1 = '{"id":"101010c90310","timestamp":"2019-02-18T18:33:35.819925957Z","station":true,"type":"call","action":"ExtraNotification","payload":{"model":"F254A","serialNumber":"1543906","vendor":"EVZ","version":"0.180601","si":"2048188","icid":"89312490184"}}';
const json2 = '[2,"4:4","ExtraNotification",{"typeModel":"553","serialNumber":"0218-009","vendor":"ABC","version":"4.0.2.14"}]';
const regex = /"vendor":"([a-zA-Z0-9]*)"/;
console.log(regex.exec(json1));
console.log(regex.exec(json2));