-7

I have a String which i have passed on via a HTTP request. However i am unable to get the value out of it. The string is as following:

var a = {"health":"img/biking_cropped.jpg","budget":"img/hip_cropped.jpg","culture":"img/old_museum_cropped.jpg"}

I am however unable to get for example the value of Health as a.health gives undefined. However a[0] only gives { back. Using JSON.parse crashes the server which it is running on.

patrick
  • 43
  • 2
  • 8
  • It's working for me: https://jsfiddle.net/vj1nqeu5/ – Gerardo Furtado Jun 01 '16 at 09:20
  • 1
    It is not a string and it is working fine https://jsfiddle.net/vasi_32/8ocbbx2r/ – brk Jun 01 '16 at 09:20
  • "The string is as following" — That isn't a string. "However a[0] only gives { back." — You wouldn't get that result from the code you provided. "Using JSON.parse crashes the server which it is running on" — In what way? What errors are reported? – Quentin Jun 01 '16 at 09:21
  • I think the problem is that i have gotten the value via a buffer and stringified it. I tried doing it another way around or changing that – patrick Jun 01 '16 at 09:27
  • that's an object, not a string pal. if string it should be: var a = "something"; – Nivesh Jun 01 '16 at 09:33
  • Possible duplicate of [JavaScript object: access variable property by name as string](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string) – Ben Fortune Jun 01 '16 at 09:47

4 Answers4

0

Here a is an object

Beside using a.health and so on you can also use for .in to get key and it;s value

var a ={
        "health":"img/biking_cropped.jpg",
       "budget":"img/hip_cropped.jpg",
       "culture":"img/old_museum_cropped.jpg"
       }

for(var keys in a){
document.write('<pre>'+keys + '--'+a[keys]+'<pre>')
}

Check this jsfiddle

Also you can use dot(.) or bracket [] notation to get the value of a key.

Probably you are trying to do a[key]. For example a['health']

brk
  • 48,835
  • 10
  • 56
  • 78
0

You'll need to pick out the values and assign the value to a variable. You can use either dot notation . or bracket notation [ ]

var a = {"health":"img/biking_cropped.jpg","budget":"img/hip_cropped.jpg","culture":"img/old_museum_cropped.jpg"};

var health = a['health'];
var budget = a.budget;
var culture = a.culture;

console.log(health +  "---- " + budget + " ---- " + culture) 
// img/biking_cropped.jpg---- img/hip_cropped.jpg ---- img/old_museum_cropped.jpg

Here's a codepen link http://codepen.io/anon/pen/LZEjme

Akinjide
  • 2,723
  • 22
  • 28
0

Use a JSON parser.there a lot of JSON parsers.

http://www.json.org/

dneranjan
  • 136
  • 1
  • 2
  • 14
0

The only reason why a[0] returns "{" is when the whole json object is a string.

var a = "abc";
console.log(a[0]); // Prints a
typeof a; //prints "string"

var b = {};
typeof b; //prints "object"

Check to see the "typeof" of the variable. It should be an object vs string.

Kiran
  • 1
  • 1