Bruno Albuquerque
Bruno Albuquerque

Reputation: 687

Javascript - Search Json Value by Key

For reasons beyond my control, I need to search for the same key value in JSONs with different structures.

I a code that is able to find the value of "valor", and no matter what is the structure of the JSON, there always will be a vendor key somewhere inside it.

By now I have two examples of JSON that I receive:

[2,"4:4","ExtraNotification",{"typeModel":"553","serialNumber":"0218-009","vendor":"ABC","version":"4.0.2.14"}]

and

{"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"}}

I've tried to map it, to check if the property is undefined or not, nothing worked.

Upvotes: 0

Views: 1964

Answers (3)

mbojko
mbojko

Reputation: 14679

You could skip the parse (or stringify it back) and search within a string. Nothing bad should happen...

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

Upvotes: 0

Marcelo Vismari
Marcelo Vismari

Reputation: 1179

I wrote a small piece of recursive code. It works for these inputs:

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"]

Upvotes: 1

Mark
Mark

Reputation: 92440

You can search through the object or array by key. If the key you're looking for is found, return it. Otherwise pass any objects found along the way back through recursively:

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

This will act like find() and return the first match found via depth first search.

Upvotes: 1

Related Questions