Home > Net >  Get value from json of which key is not known (Javascript)
Get value from json of which key is not known (Javascript)

Time:04-22

I have following JSON file:

{
  "status": 200,
  "msg": "OK",
  "result": {
    "files": {
      "count": 1,
      "pUnJbKzql0f2": {
        "name": "How do I access this",
        "active": "yes"
      }
    }
  }
}

I have to access the value of key name in above JSON file. The problem is that the key pUnJbKzql0f2 keeps changing every time the file is requested. I don't have control over the json file. So how do I access key name. Talking about PHP we can use array_keys or array_key_exists function, however I want javascript specific answer for it.

json['result']['files'][what should I put here]['name']

                      ^^^^^^^^^^^^^^^^^^^^^^^

Please if someone could post a solution here.

CodePudding user response:

You have to examine the contents of .result.files. This can be done using a for-in loop where the keys are read.

This snippet illustrates finding the unknown key (and it's value) based on it not being the known key count. If the object has more properties you will have to devise a way of excluding those except the one you want.

let requiredKey = "";
let requiredName = "";
const obj = {
  "status": 200,
  "msg": "OK",
  "result": {
    "files": {
      "count": 1,
      "pUnJbKzql0f2": {
        "name": "How do I access this",
        "active": "yes"
      }
    }
  }
}

files = obj.result.files // and object with 2 properties

 for (key in files) {
 
 if (key != "count") {
 
 requiredKey = key;
 requiredName = files[key].name

 } // end if;
      
 } // next key in files

 console.log(`${requiredKey} with name property: ${requiredName}`)

  • Related