JavaScript JSON 数据处理

时间:2022-03-24 20:10:58
  • 在JavaScript 也自带了 JSON 格式的处理

    <!doctype html>
<html> <script>
var test_json_str =
{
"name" : "chen",
"age" : 18,
"sex" : "man"
} // json obj ---> json str JSON 类转换为字符串
str_json1 = JSON.stringify(test_json_str);
document.write("str_json1:<br>");
document.write(str_json1);
document.write("<br>");
document.write(test_json_str);
document.write("<br>");
document.write("<br>"); // json str ---> json obj 字符串转换为类
var obj = JSON.parse(str_json1);
document.write("old mesage: <br>");
document.write(obj["name"]);
document.write("<br>");
document.write(obj["age"]);
document.write("<br>");
document.write(obj["sex"]);
document.write("<br>");
//document.write(obj); // change obj 修该 JSON 类的属性
obj["name"] = "chenfulin";
obj["age"] = 100;
obj["sex"] = "manman"; document.write("<br>");
document.write("new json obj: <br>");
document.write(obj["name"]);
document.write("<br>");
document.write(obj["age"]);
document.write("<br>");
document.write(obj["sex"]);
document.write("<br>"); document.write("<br>");
document.write("new json string: <br>");
// json obj ---> json str JSON 类转换为字符串
str_json1 = JSON.stringify(obj);
document.write(str_json1); </script> </html>
  • 后有如下显示:

    str_json1:
{"name":"chen","age":18,"sex":"man"} // 这是显示 转换后的字符串
[object Object] // 直接写这个 obj 会显示这个 old mesage: // 显示老的 JSON 类的内容
chen
18
man new json obj: // 修改 JSON 类
chenfulin
100
manman new json string:
{"name":"chenfulin","age":100,"sex":"manman"} //再 转换成字符串输出