简体   繁体   English

如何将JSON序列化的对象转换为JS对象,以便可以访问其属性?

[英]How do I convert a JSON serialized object into a JS object, so I can access its properties?

In my JavaScript I want to access the properties of a JSON serialized object that was produced via a .NET web service. 在我的JavaScript中,我想访问通过.NET Web服务生成的JSON序列化对象的属性。 How do I deserialize the JSON data into an object that I can manipulate in JavaScript? 如何将JSON数据反序列化为可以在JavaScript中操作的对象?

Use json2.js from http://json.org -- it provides a JSON object on the global object that provides a parse function. 使用来自http://json.org的 json2.js -它在提供parse功能的全局对象上提供JSON对象。 It has the added advantage of being the basis for the ES3.1 specification of JSON, and will use a native implementation of JSON if possible. 它具有作为JSON ES3.1规范的基础的附加优点,并且在可能的情况下将使用JSON的本机实现。 This means that you can parse a json serialised object with: 这意味着您可以使用以下方法解析json序列化对象:

object = JSON.parse(string)

Because of the way it is implemented this means if you page is viewed in a browser that supports JSON (eg. Safari 4, Firefox 3.5, even IE8) you will get a fast and secure parser automatically. 由于它的实现方式,这意味着如果您在支持JSON的浏览器(例如Safari 4,Firefox 3.5,甚至IE8)中浏览网页,您将自动获得快速, 安全的解析器。

You could use jQuery and do the web service call via getJSON 您可以使用jQuery并通过getJSON进行 Web服务调用

Or you could use the official json parser . 或者,您可以使用官方的json解析器

Try Dojo.json package. 尝试使用Dojo.json包。 It contains toJson() and fromJson() functions. 它包含toJson()和fromJson()函数。

You shouldn't use eval() unless you really trust your data provider. 除非您真正信任数据提供者,否则不应使用eval()。 eval() can evaluate functions and call them, can raise random exceptions etc. Use libraries and you'll be on the safer side. eval()可以评估函数并调用它们,可以引发随机异常等。使用库,您会更加安全。

EDIT:: 编辑::

crescentfresh pointed out that dojo.fromJson() is just a wrapper for eval() . crescentfresh指出dojo.fromJson()只是eval()的包装。 That's true, sadly, but even at JSON.org they say that eval() can be a security issue, and they should know what they're talking about :) 不幸的是,这是事实,但是即使在JSON.org上,他们也说eval()可能是一个安全问题,他们应该知道他们在说什么:)

You can use external JSON parser (see: code.google.com/p/json-sans-eval for example), or just use dojo.fromJson() and hope they'll improve it in next version 您可以使用外部JSON解析器(例如:请参阅code.google.com/p/json-sans-eval ),也可以只使用dojo.fromJson()并希望他们在下一个版本中对其进行改进

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

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