用Java脚本访问Json [英] Accessing Json in Javascript

查看:99
本文介绍了用Java脚本访问Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

'[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]'

当我尝试像这样访问上面的内容时:

When I try to access the above like this:

for (var i = 0; i < data.length; i++) {
    alert(data[i]);
}

它阐明了每件事,例如[, {, ", S等.

It spells out each thing, such as [, {, ", S, and etc.

我也尝试做data[i].SponsorName,但是显然得到了undefined.我应该如何访问它?

I also tried doing data[i].SponsorName but obviously got undefined. How should I be accessing this?

推荐答案

您需要解析JSON字符串,最好使用JSON.parse解析. JSON API内置于更现代的浏览器中,可以通过包含 Crockford的JSON脚本来提供给较旧的浏览器. Crockford的脚本将检测浏览器是否已经提供了API,如果没有,则将其添加.

You need to parse the JSON string, preferably with JSON.parse. The JSON API is built into more modern browsers and can be provided to older browsers by including Crockford's JSON script. Crockford's script will detect if the browser already provides the API and adds it if not.

将其放置在适当的位置,如果您的JSON在名为response的字符串变量中,则可以:

With that in place, if your JSON is in a string variable named response, you can:

var parsedResponse = JSON.parse( response );
//run your iterating code on parsedResponse

这篇关于用Java脚本访问Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆