如何在 Javascript 中解析 Json 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8211813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parsing Json Array in Javascript?
提问by Gendaful
Json Array as following is easy to parse,
如下的 Json Array 很容易解析,
{
"movieCategories": [
"a" : "Animation",
"b" :"Romance",
"c" :"Science Fiction"
"d" : "Western"
]
}
Now,I have a Json response as following which is stored in movies.json file.
现在,我有如下的 Json 响应,它存储在 movie.json 文件中。
{
"movieCategories": [
"Animation",
"Romance",
"Science Fiction",
"Western"
]
}
I am not sure how to parse the above json array. Kindly help.
我不确定如何解析上面的 json 数组。请帮忙。
Thank you.
谢谢你。
回答by Gfox
Assume
认为
var test = {
"movieCategories": [
"Animation",
"Romance",
"Science Fiction"
"Western"
]
}
then
然后
test.movieCategories[0] // Will be Animation
回答by Moe Sweet
Download json2.js from here https://github.com/douglascrockford/JSON-jsInclude it on your page. Use like this
从这里下载 json2.js https://github.com/douglascrockford/JSON-js 将其包含在您的页面上。像这样使用
jsonobj = JSON.parse(jsonstring);
jsonstring = JSON.stringify(jsonobj);
回答by PiTheNumber
According to JSLintthis is invalid JSON. There is a "," missing:
根据JSLint,这是无效的 JSON。缺少一个“,”:
{ "movieCategories": [ "Animation", "Romance", "Science Fiction", "Western" ] }
For the rest see: Is it possible to parse JSON with javascript?
回答by shenhengbin
you can only use the eval like
你只能使用 eval 之类的
<html>
<div>
<script language="javascript">
var arr = '[{ "movieCategories": [ "Animation", "Romance", "Science Fiction" ,"Western" ] }]';
var b = eval(arr)[0];
alert(b.movieCategories);
</script>
</div>
</html>