Home  >  Article  >  Web Front-end  >  What are the json methods in javascript

What are the json methods in javascript

青灯夜游
青灯夜游Original
2021-06-18 13:51:403747browse

javascript中的json方法:1、“JSON.parse()”方法,用于将一个JSON字符串转换为JavaScript对象;2、“JSON.stringify()”方法,用于将JavaScript值转换为JSON字符串。

"What

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,是理想的数据交换格式。同时,JSON是 JavaScript 原生格式,这意味着在 JavaScript 中处理 JSON数据不须要任何特殊的 API 或工具包。

基础结构

必须使用双引号"包含键值

// 键值对的集合,值的有序列表
var JsonObj = {"name":"Hannah", "like":["看书", "电影", "晨跑"]};

数组

var jsonArr = [
  {
    "name": "tom",
    "type": "cat"
  },
  {
    "name": "jack",
    "type": "mouse"
  }
]

对象

var jsonObj = {
  "like": ["看书", "电影", "晨跑"],
  "book": ["数字城堡", "刻意练习", "老人与海"]
}

javascript中的json方法

字符串转对象

var jsonObject= JSON.parse(jsonstr);

对象转字符串

var jsonstr =JSON.stringify(jsonObject);

优雅的输出格式

JSON.stringify() 方法的可选参数space,可以指定缩进用的空白字符串,用于美化输出(pretty-print)space参数是个数字,它代表有多少的空格;上限为10。该值若小于1,则意味着没有空格;如果该参数没有提供(或者为null)将没有空格。

// replacer 分隔符 space 缩进
JSON.stringify(value[, replacer [, space]])

var formatJsonStr=JSON.stringify(jsonObject,undefined, 2);

JSON字符串的替换

工作经常遇到这样的字符串,如下:

"What

需要经过替换后,才能从字符串转化成JSON对象。这里我们需要用JS实现replaceAll的功能, 将所有的 ’ \" ’ 替换成 ’ " ’ .
代码如下,这里的gm是固定的,g表示global,m表示multiple:

var jsonStr=jsonStr.replace(new RegExp('\\"',"gm"), '"' );

替换后的效果如下:

"What

遍历JSON对象和JSON数组

// 遍历JSON对象
var packJson  = {
  "name":"Liza", 
  "password":"123"
};
for(var k in packJson ){  //遍历packJson 对象的每个key/value对,k为key
  alert(k + " " + packJson[k]);
}

// 遍历JSON数组
var packJson = [
  {
    "name":"Liza", 
    "password":"123"
  },
  {
    "name":"Mike", 
    "password":"456"
  }
];
for(var i in packJson){  //遍历packJson 数组时,i为索引
  alert(packJson[i].name + " " + packJson[i].password);
}

【相关推荐:javascript学习教程

The above is the detailed content of What are the json methods in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn