-1

This might be a silly question but I did not found any answers for it. How can I get the parent's name from this json for example ?

{ 
 "someParentName":{
   "somechild":{
     "value1":"test"
   }
 }
}

So how can i log the "someParentName" ? Any language would be good but i am using JS.

Angelo
  • 195
  • 1
  • 15
  • Could you give an example where you would want to do this? Might help on giving a better answer. – Segers-Ian Apr 10 '19 at 11:12
  • Yeah you won't find any answers because you're probably searching for "parse JSON blah blah", and there is no parsing nor JSON here. If you looked up "how to get the keys from a javascript object" you'd be on the right track – James Apr 10 '19 at 11:38

4 Answers4

1

Right now it's not a JSON, it's already an object. That's fine. The Object.keys method will give you all the top-level property names (so, here, ["someParentName"]). Is this what you're after?

const obj = {
  "someParentName": {
    "somechild": {
      "value1": "test"
    }
  }
}

console.log(Object.keys(obj));
mbojko
  • 13,503
  • 1
  • 16
  • 26
1

var data = { 
 "someParentName":{
   "somechild":{
     "value1":"test"
   }
 }
}
var parent_key = Object.keys(data)[0]

console.log(data[parent_key]);
1

If your object has a single key, then you can use Object.keys(obj)[0], otherwise, using Object.keys() will return an array of all keys at root level:

const obj = { 
 "someParentName":{
   "somechild":{
     "value1":"test"
   }
 }
}

console.log(Object.keys(obj)[0]);
jo_va
  • 13,504
  • 3
  • 23
  • 47
0

Try this:

console.log(data.someParentName.somechild.value1);

where

var data = { 
 "someParentName":{
   "somechild":{
     "value1":"test"
   }
 }
}

there was a lot of these on stackoverflow

How to access elements of json array using javascript/jquery? [closed]