4, JSON.stringify () --- the JavaScript object into a string json

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/LOVEYSUXIN/article/details/102730511

4、JSON.stringify()

When transmitting data to a web server, the data must be a string.
By the JSON.stringify () converts a string JavaScript object.

JavaScript object to a string of

There obj object in JavaScript:

var obj = { name:"Bill Gates", age:62, city:"Seattle"};

JavaScript function using the JSON.stringify () to convert it to a string.

var myJSON = JSON.stringify(obj);

The result will be to comply with a string JSON notation.

Stringify JavaScript array

It can also be carried out on a string of JavaScript array:

I have this array in JavaScript:

var arr = [ "Bill Gates", "Steve Jobs", "Elon Musk" ];

JavaScript function using the JSON.stringify () to convert it to a string.

var myJSON = JSON.stringify(arr);

The result will be a string comply with JSON notation.

myJSON currently is a piece of string, and is ready to sent to the server.

Date of string

In JSON, the object is not allowed to date. The JSON.stringify () function will convert any date string.

<script>
var obj = { name: "Bill Gates", today: new Date(), city: "Seattle" };
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

输出:
{"name":"Bill Gates","today":"2019-10-24T10:33:02.054Z","city":"Seattle"}
Function stringified

In JSON not allowed as a function of object values.

Should be avoided in JSON function, the function will lose its scope, but you also need to use eval () function to convert them back.

JSON.stringify () function will remove any JavaScript object functions, including keys and values:

<script>
var obj = { name: "Bill Gates", age: function () {return 62;}, city: "Seattle" };
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

输出:
{"name":"Bill Gates","city":"Seattle"}

<script>
var obj = { name: "Bill Gates", age: function () {return 62;}, city: "Seattle" };
//把函数转换为字符串,就可以在 JSON 对象中保留该函数
obj.age = obj.age.toString();  
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

输出json:
{"name":"Bill Gates","age":"function () {return 62;}","city":"Seattle"}

Guess you like

Origin blog.csdn.net/LOVEYSUXIN/article/details/102730511