Javascript 如何将 JS 对象转换为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39174022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert JS Object to JSON
提问by Stefan Bürscher
Is it posible to convert a js object to json or is a js object exactly a JSON ? Can someone tell me what a JSON exactly is ?
是否可以将 js 对象转换为 json 或者 js 对象完全是 JSON ?有人能告诉我 JSON 到底是什么吗?
回答by Marc B
Quite literally, JSON is a stricter format for what is basically the right-hand side of a Javascript variable assignment. It's a text-based encoding of Javascript data:
从字面上看,JSON 是一种更严格的格式,基本上是 Javascript 变量赋值的右侧。它是基于文本的 Javascript 数据编码:
var foo = ...json goes here ...;
JSON can be ANYvalid Javascript data-only structure. A boolean, an int, a string, even arrays and objects. What JSON ISN'Tis a general serialization format. Something like this
JSON 可以是任何有效的 Javascript 纯数据结构。一个布尔值、一个整数、一个字符串,甚至是数组和对象。什么 JSON不是一般的序列化格式。像这样的东西
var foo = new Date();
json = JSON.stringify(foo); // json gets the string "2016-08-26 etc..."
newfoo = JSON.parse(json); // newfoo is now a string, NOT a "Date" object.
will not work. The Date object will get serialized to a JSON string, but deserializing the string does NOT give you a Date
object again. It'll just be a string.
不管用。Date 对象将被序列化为 JSON 字符串,但反序列化该字符串不会Date
再次为您提供对象。它只是一个字符串。
JSON can only represent DATA, not CODE. That includes expressions
JSON 只能表示 DATA,不能表示 CODE。这包括表达式
var foo = 2; // "2" is valid json
var foo = 1+1; // invalid - json does not have expressions.
var foo = {"bar":["baz"]}; // also valid JSON
var foo = [1,2,3+4]; // fails - 3+4 is an expression
回答by Nalin Aggarwal
To convert JS data object to JSON , you can use JSON.stringify()
要将 JS 数据对象转换为 JSON ,您可以使用 JSON.stringify()
Exmaple
例子
Input :-
输入 :-
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
JSON.stringify(person)
Output:
输出:
"{"firstName":"John","lastName":"Doe","age":50,"eyeColor":"blue"}"