简体   繁体   English

解析Javascript中的多级JSON字符串

[英]Parse multilevel JSON String in Javascript

I want to parse the following JSON string in Javascript: 我想在Javascript中解析以下JSON字符串:

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

I normally parse JSON strings like this: 我通常会这样解析JSON字符串:

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? 如何解析此类JSON字符串?

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. 由于str已经是一个对象,因此无需再次parse() ,这将导致错误。
  2. Since weather is an array, You need to use index to access array's element. 由于weather是一个数组,因此您需要使用index来访问数组的元素。

您需要创建一个像这样的数组:

alert(str.weather[0].description);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM