简体   繁体   中英

Is it possible to return JSON key names based on value without knowing the key's name

Say I have the following JSON file:

{"attributes":
   {
   "blue":true,
   "red":false,
   "green":true,
   "webAtt":
      {
      "webColor": "#EF5689",
      "webSafe":true
      }
   }
}

but lets also say I do not know any JSON nodes except "attributes". How would I go about finding which attributes are true? Is this even possible? If not, must it be hardcoded for each child node of "attributes"?

I would like this done in JavaScript if possible.

EDIT: There is a reason why webAtt is there and its because I want to get "websafe" and not "webAtt" when sweeping.

Object.keys() returns the enumerable properties of the given object. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

So you can do Object.keys(obj.attributes) on the object above and it would return ["blue", "red", "green"] . You can then apply a filter to return only the attributes where the value in the object is true .

 var obj = { "attributes": { "blue":true, "red":false, "green":true } } console.log(Object.keys(obj.attributes).filter(function(attr) { return obj.attributes[attr] })) 

You can do this with a for loop.

 var json = {"attributes": { "blue":true, "red":false, "green":true, "webAtt": { "webSafe":true, "webcolor":"#EF5689" } } }; for (var k in json.attributes) { if(json.attributes[k]==true){ console.log(k + ' ' + json.attributes[k]); } if(whatIsIt(json.attributes[k])=="Object"){ for(var l in json.attributes[k]){ if(json.attributes[k][l]==true){ console.log(l+' '+json.attributes[k][l]); } } } } //See credit below snippet var stringConstructor = "test".constructor; var arrayConstructor = [].constructor; var objectConstructor = {}.constructor; function whatIsIt(object) { if (object === null) { return "null"; } else if (object === undefined) { return "undefined"; } else if (object.constructor === stringConstructor) { return "String"; } else if (object.constructor === arrayConstructor) { return "Array"; } else if (object.constructor === objectConstructor) { return "Object"; } else { return "don't know"; } } 

Credit for JSON object type Identifier code: How to check if JavaScript object is JSON

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM