<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSON对象和字符串的转化</title>
<script type="text/javascript">
//1.json字符串转成对象[取值方便]
console.log(‘1.json字符串转成对象‘);
var str1=‘{"firstName":"hr","lastName":"w"}‘;
//通过调用对象的属性获取值
var JsonObj1=JSON.parse(str1);//把字符串转成对象数组
console.log(str1);
console.log(JsonObj1.firstName);
console.log(JsonObj1.lastName);
//2.json对象转成字符串
console.log(‘-----------------‘);
console.log(‘2.json对象转成字符串‘);
var str2=JSON.stringify(JsonObj1);
console.log(‘str2‘+str2);
//3.遍历数组json
var str3=‘[{"firstName":"hr","lastName":"w"},{"firstName":"jp","lastName":"x"},{"firstName":"Bill","lastName":"Gates"}]‘;
//把字符串转成对象
var persons=JSON.parse(str3);
console.log(‘persons.length:‘+persons.length);
for(var i=0;i<persons.length;i++){
console.log(persons[i].lastName);
}
</script>
</head>
<link rel="shortcut icon" href="#" />
<body>
</body>
</html>

原文:https://www.cnblogs.com/whr-blogs/p/12188485.html