0

it's common to have json keys without spaces. I can access a value of a json simply calling it's key. But if my json looks like

{
     "kemon acho": "I am fine"
}

How can I print I am fine ? Thank you.

bhansa
  • 6,780
  • 2
  • 27
  • 49
Hkm Sadek
  • 2,558
  • 6
  • 37
  • 81

4 Answers4

4

You just do:

var j = { "kemon acho": "I am fine" };
console.log(j["kemon acho"]);
Faly
  • 12,802
  • 1
  • 18
  • 35
  • Great. I tried to print using the plain texts and gave me error now using variable like 'j' works perfectly. Another thing, how can I print the key itself and not the value? – Hkm Sadek Sep 30 '17 at 07:41
  • You get all the keys of the object by: var keys = Object.keys(j); keys is an array here – Faly Sep 30 '17 at 07:43
3

Simply use squared brackets notation:

myJSON["kemon acho"]

Property AccessorsMDN

Roko C. Buljan
  • 180,066
  • 36
  • 283
  • 292
1

You can access the property value, but if you have control over your JSON, use camel case or underscore case. They're more robust.

var j = {
   "kemon acho": "I am fine"
}

console.log( j["kemon acho"] );

A better JSON structure would be camel case:

var j = {
   "kemonAcho": "I am fine"
}

or underscore case:

var j = {
   "kemon_acho": "I am fine"
}
Adam Azad
  • 10,915
  • 5
  • 26
  • 67
0

Use square brackets like this:

data = {
     "kemon acho": "I am fine"
}

cosole.log(data["kemon acho"])
Prakash Sharma
  • 13,640
  • 3
  • 28
  • 35