我一直对何时使用这两种解析方法感到困惑。
在我回显json_encoded数据并通过ajax检索它之后,我经常对何时应该使用JSON感到困惑。stringify和JSON.parse。
我得到[对象,对象]在我的控制台.log解析和JavaScript对象时stringized。
$.ajax({
url: "demo_test.txt",
success: function(data) {
console.log(JSON.stringify(data))
/* OR */
console.log(JSON.parse(data))
//this is what I am unsure about?
}
});
JavaScript对象<-> JSON字符串
JSON.stringify() <-> JSON.parse()
JSON.stringify(obj) -接受任何可序列化的对象,并将JSON表示形式作为字符串返回。
JSON.stringify() -> Object To String.
JSON.parse(string) -接受格式良好的JSON字符串并返回相应的JavaScript对象。
JSON.parse() -> String To Object.
解释:
JSON。stringify(obj[,转换器[,空间]]);
Replacer/Space -可选或接受整数值,也可以调用整型返回函数。
function replacer(key, value) {
if (typeof value === 'number' && !isFinite(value)) {
return String(value);
}
return value;
}
用于将非有限的no替换为null。
使用空格缩进Json字符串
这里真正的困惑不是关于parse和stringify,而是关于成功回调的数据参数的数据类型。
data可以是原始响应,即字符串,也可以是JavaScript对象,如文档所示:
成功
类型:函数(任何数据,字符串textStatus, jqXHR jqXHR
函数在请求成功时调用。函数得到
传递三个参数:从服务器返回的数据,格式化
根据dataType参数或dataFilter回调
函数(如果指定)
dataType默认设置为intelligent guess
数据类型(默认:智能猜测(xml, json,脚本或html))
类返回的数据类型
服务器。如果没有指定,jQuery将尝试基于
响应的MIME类型(在1.4中,XML MIME类型将生成XML
JSON会产生一个JavaScript对象,在1.4脚本中会执行
脚本,以及任何其他将作为字符串返回)。
JSON.parse()接受JSON字符串并将其转换为JavaScript对象。
JSON.stringify()接受一个JavaScript对象并将其转换为JSON字符串。
const myObj = {
name: 'bipon',
age: 25,
favoriteFood: 'fish curry'
};
const myObjStr = JSON.stringify(myObj);
console.log(myObjStr);
// "{"name":"bipon","age":26,"favoriteFood":"fish curry"}"
console.log(JSON.parse(myObjStr));
// Object {name:"bipon",age:26,favoriteFood:"fish curry"}
And although the methods are usually used on objects, they can also be used on arrays:
const myArr = ['simon', 'gomez', 'john'];
const myArrStr = JSON.stringify(myArr);
console.log(myArrStr);
// "["simon","gomez","john"]"
console.log(JSON.parse(myArrStr));
// ["simon","gomez","john"]