解析JSON响应问题 [英] Parsing JSON response problem

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

问题描述

我有一个JSON响应,其格式为..

I've got a JSON response in the format of..

{"item":{"cid":544,"id":3023,"name":"names"},"success":1,"msg":""}

响应存储为s.当我做...

The response is stored as s. When I do...

var obj = eval('('+s+')');

obj = undefined.因此是obj.name = undefined

我想从此JSON响应中获取idname.为什么我不工作?我如何使其正常工作"?

I want to get id and name from this JSON response. Why is what I'm doing not working? How do I "make it work"?

推荐答案

不建议使用eval(出于安全考虑),请使用JSON解析器:

eval is not recommended (security wise), use the JSON parser:

var obj = JSON.parse(result);

或确保即使浏览器没有JSON解析器也能正常工作:

or to be sure that it works even if the browser does not have a JSON parser:

var obj = typeof JSON !='undefined' ?  JSON.parse(result) : eval('('+result+')');

但是,不建议这样做,在这种情况下,您应该更喜欢按照此答案注释中的建议包括备用JSON库(请参见 json.org ).

This is however not recommended and you should in that case prefer to include an alternate JSON library as recommended in this answer comments (see json.org).

然后您可以执行以下操作:

Then you can do:

var id = obj.item.cid;
var name = obj.item.name;

这篇关于解析JSON响应问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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