知优码

您现在的位置是:首页 > WEB相关 > Json格式

Json格式

json对象和json字符串之间的转化

知优码 2019-11-17Json格式
json字符串----->json对象使用JSON.parse()函数var jsonStr = '{"name":"zhangsan","age":23,"email":"chentging@ali
  1. json字符串----->json对象
    • 使用JSON.parse()函数

      var jsonStr = '{"name":"zhangsan","age":23,"email":"chentging@aliyun.com"}';
      var json = JSON.parse(jsonStr);
      console.log(json);//输出:Object {name: "zhangsan", age: 23, email: "chentging@aliyun.com"}
    • 使用eval()函数

      var jsonStr = '{"name":"zhangsan","age":23,"email":"chentging@aliyun.com"}';
      var json = eval ("(" + jsonStr + ")");
      console.log(json);//输出:Object {name: "zhangsan", age: 23, email: "chentging@aliyun.com"}
    • 使用jQuery插件jQuery.parseJSON()

      var jsonStr = '{"name":"zhangsan","age":23,"email":"chentging@aliyun.com"}';
      var json = jQuery.parseJSON(jsonStr);
      console.log(json);//输出:Object {name: "zhangsan", age: 23, email: "chentging@aliyun.com"}
  2. json对象------>json字符串
    • 使用JSON.stringify()

      var json = {name: "zhangsan", age: 23, email: "chentging@aliyun.com"};
      var jsonStr = JSON.stringify(json);
      console.log(jsonStr);//输出:"{"name":"zhangsan","age":23,"email":"chentging@aliyun.com"}"
  3. 把数据在前后端之间传递,需要把json对象转换为json字符串