简体   繁体   English

Javascript JSON.parse或直接访问

[英]Javascript JSON.parse or directly access

When we can read a property directly from string: 当我们可以直接从字符串读取属性时:

var data = {"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}};
console.log(data.address.streetName); // cde

Why do people use JSON.parse : 人们为什么使用JSON.parse

var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde

It is not a string, but Javascript object. 它不是字符串,而是Javascript对象。 String is given below 字符串如下

var data = '{"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}}';

to make it object we use JSON.parse 为了使其成为对象,我们使用JSON.parse

var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde

In your first example, data is an object, but in your second example, data is a JSON string . 在第一个示例中,data是一个对象,但是在第二个示例中,data是JSON string

That's a major difference. 那是一个很大的不同。 You could call eval(data) to parse a JSON string, but that's very unsafe. 可以调用eval(data)来解析JSON字符串,但这是非常不安全的。

JSON.parse() expects a string. JSON.parse()需要一个字符串。 More specifically, a string with a JSON-encoded piece of data. 更具体地说,是带有JSON编码数据段的字符串。

If it's applied to an object then it's an error, the source of which is probably the common confusion that seems to exist between JavaScript objects and the JSON format. 如果将其应用于对象,则表示错误,其来源可能是JavaScript对象和JSON格式之间似乎存在的常见混淆。

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

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