Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search a JSON file's key case insensititvely

I have a JSON object like below,

"Data Center": {
        "TMSLevel2": {
            "Comp-NX2/4/5/6K": "NX2/4/5/6K",
            "Comp-NX3K": "NX3K",
            "Comp-NX7K": "NX7K",
            "Comp-NX9K": "NX9K",
            "Comp-ACI": "ACI"
         }
}

I named the file as map.js and import it by var map = require ('./map.js') from Node JS. I am accessing it like console.log(map["Data center"]["TMSLevel2"][name]). Now the name be "Comp-NX3K" or "Comp-NX3k" or "Comp-nx3K".

When it is "Comp-NX3K" it prints the corresponding value. But, if it is "Comp-nx3K" it prints "undefined" as there is no matching value. How to fix it ??

like image 600
Anijit Sau Avatar asked Nov 21 '16 05:11

Anijit Sau


People also ask

Is JSON keys are case sensitive?

JSON is case-sensitive. SQL is case-insensitive, but names in SQL code are implicitly uppercase.

Can JSON keys have capital letters?

You Don't Have to Be. You must have learned capitalization rules in your grammar school, but the real-world search is not so sensitive to capitalization.


1 Answers

JavaScript object attributes are case sensitive, which means that JSON keys are also case sensitive. However, assuming you don't have a gargantuan list, then you could use Object.keys, Object.values, and create a lower-cased index.

var searchedFor = ("NX3K").toLowerCase(); // make sure to have them match case
var data =  {
            "Comp-NX2/4/5/6K": "NX2/4/5/6K",
            "Comp-NX3K": "NX3K",
            "Comp-NX7K": "NX7K",
            "Comp-NX9K": "NX9K",
            "Comp-ACI": "ACI"
         };
var iKeys = Object.keys(data) // this is a list of all of the attributed above (Comp-…)
               .map( // this calls a function on every member of an Array
                  function(x){ // this function returns a lower cased version of whatever
                               // value it was given
                      return x.toLowerCase();});

// iKeys is now an array of lower-cased keys.
var myValue = Object.values(data)[
                      // wherever the searched for element shows up, 
                      // will correspond to that value.
                      iKeys.indexOf(searchedFor)];

I do have to warn you, the above will only match the first instance of the key. So if there are cases of Comp-NX9K and Comp-nx9k you'll only get one.

like image 94
cwallenpoole Avatar answered Oct 29 '22 04:10

cwallenpoole