1、JSON对象 转化为 JSON字符串
- JSON.stringify()方法进行转换
let jsonStr = JSON.stringify(jsonObj);
// for example
let obj = {'name':'lucy', 'age':8,'sex':'female'};
let str = JSON.stringify(obj);
console.log(str) // "{"name":"lucy","age":8,"sex":"female"}";
2、JSON字符串 转化为 JSON对象
- eval()方法进行转换
let jsonObj = eval('(' + jsonStr + ')');
// for example
let str = '{a:1,b:2}';
eval('(' + str + ')'); //需要在字符串外包裹一对括号(), {a: 1, b: 2}
- JSON.parse()方法进行转换
// 原生方法
let jsonObj = JSON.parse(jsonStr);
// jquery方法
let jsonObj = $.parseJSON(jsonStr);
// for example
var str = '{"name":"lucy", "age":8,"sex":"female"}';
JSON.parse(str); //{name: "lucy", age: 8, sex: "female"}
使用JSON.parse()需要注意一点,此方法是将JSON字符串转换成对象,所以字符串必须符合JSON格式,即键值都必须使用双引号包裹:
```
let a = '["1","2"]';
console.log(JSON.parse(a)); // ["1", "2"]
let b = "['1','2']";
console.log(JSON.parse(b)); // 报错
```
3、JSON对象 转化为 JSON数组
// 循环,键值都保留
// {'name':'lucy', 'age':8,'sex':'female'}
// [{name: 'lucy},{age: 8}, {sex: "female"}]
let jsonObj={'name':'lucy', 'age':8,'sex':'female'};
function objToArray(array) {
var arr = [];
for (var i in array) {
var o={};
o[i]=array[i];
arr.push(o);
}
return arr;
}
let jsonArr = objToArray(jsonObj);
console.log(jsonArr ); // [{name: 'lucy},{age: 8}, {sex: "female"}]
4、JSON数组 转化为 JSON对象
var arr = ['lucy', 8, 'female'];
var json= {};
for (var i = 0; i < arr.length; i++) {
json["属性" + i] = arr[i];
}
let jsonObj= JSON.stringify(json);
console.log(jsonObj); // {"属性0":"lucy","属性1":8,"属性2":"female"}