-1

I want to parse the following JSON string in Javascript:

str = {
    "weather":[{
        "id":803,
        "main":"Clouds",
        "description":"broken clouds",
        "icon":"04d"
    }],
    "cod":200
}

I normally parse JSON strings like this:

var obj = JSON.parse(str);
alert(obj.weather.description);

But in this case it doesn't work for me. How do I have parse such JSON strings?

Pierre C.
  • 1,426
  • 1
  • 11
  • 20
Pascal
  • 1,255
  • 5
  • 20
  • 44
  • 1
    This is not a JSON string, this is an object – drys Apr 14 '16 at 07:55
  • Possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – JJJ Apr 14 '16 at 07:55
  • If you have problems understanding the structure after parsing, assign it to a global variable and then play with it in console. – Mike B Apr 14 '16 at 07:58
  • Possible duplicate of [Safely turning a JSON string into an object](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – Pascal Oct 21 '16 at 10:28

2 Answers2

4

You just need to use

alert(str.weather[0].description);
  1. As str is already an object, you don't need to parse() it again, this will result in an error.
  2. Since weather is an array, You need to use index to access array's element.
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

You need to create an array like this:

alert(str.weather[0].description);
Pascal
  • 1,255
  • 5
  • 20
  • 44
Hemangi Satasiya
  • 53
  • 1
  • 2
  • 8