JSON objects and strings

JSON objects and strings

Paste from: https://www.cnblogs.com/cstao110/p/3762056.html

Q: What is "JSON string" and what is "JSON object", ** difference between the two?

  • JSON format objects can be used directly JQuery operations, such as may be used in C # object (class name) point out the property (Method) as
  • JSON string is just a string, as a whole, is not taken, then no way to remove the data stored therein, can not directly use, unless you just want to alert (him);

JSON object:

var str2 = { "name": "deluyi", "sex": "man" };

JSON string:

var str1 = '{ "name": "deyuyi", "sex": "man" }';

Q: The "JSON string" into a "JSON object" approach?

A: Use $ .parseJSON (str)

//由JSON字符串转换为JSON对象
var str='{ "name": "John" }';
var obj = jQuery.parseJSON(str)
alert("1"+ obj.name);

ps: this way only supports standard formats: var str = '{ "name": "John"}';

二:JSON.parse(str)

var str = '{ "name": "mady", "age": "24" }';
var obj = JSON.parse(str);
alert(obj.name);

ps: this way only supports standard formats: var str = '{ "name": "John"}';

3: Use eval ( '(' + str + ')');

//由JSON字符串转换为JSON对象
var str='{ "name": "John" }';
var obj = eval('(' + str + ')'); 
alert( obj.name);

var str2="{ 'name': 'John' }";
var obj2 = eval('(' + str2 + ')'); 
alert( obj2.name);

var str3="{ name: 'John' }";
var obj3 = eval('(' + str3 + ')'); 
alert( obj3.name); 

Eval embodiment can convert the standard and non-standard format strings:

var str="{ 'name': 'John' }";
var str2='{ "name": "John" }';
var str3="{ name: 'John' }";

Q: The "JSON object" into a method "JSON string" of?

Using the JSON.stringify global method () and the toJSONString ()

E.g:

var last=obj.toJSONString(); //将JSON对象转化为JSON字符

or

var last=JSON.stringify(obj); //将JSON对象转化为JSON字符

Q: reading JSON object methods?

As the above example:

var str2 = { "name": "mady", "sex": "man" };

It can be read this way:

alert(str2.name);//和C#一样直接往出点…

Pop-up "mady".

JSON we rarely encountered such a simple, such as a bit of a complex JSON object (such as nested type of JSON:

var str={"GetUserPostByIdResult":{"Age":"33","ID":"2server","Name":"mady"}};

Resolved with:

alert(str.GetUserPostByIdResult.Name);//一次点不出来,我多点几次

Pop: "mady".

Guess you like

Origin www.cnblogs.com/youpeng/p/10991911.html