JSON语法可以分为三种类型:
简单值
数字(整数或浮点数)
字符串(在双引号中)
逻辑值(true 或 false)
对象
对象(在花括号中)
null
数组
数组(在方括号中)
简单值
数字类型与字符串类型
5 //数字
"Hello World" //字符串
true //真假
JavaScript字符串与JSON字符串的最大区别在于,JSON字符串必须使用双引号
对象:
JSON中的对象与JavaScript字面量稍微有一些不同。下面是一个JavaScript中的对象字面量
//JavaScript对象
var person={
name:"Qianwei",
age:22
}
json对象要给属性加引号
//json对象
{
"name":"Qianwei",
"age":22
}
//json对象
{
"name": "Qianwei",
"age": 22,
"school": {
"name": "anqing",
"lOaction": "Anqing"
}
}
数组:
JSON中的第二种复杂数据类型是数组。JSON数组采用的就是JavaScript中的数组字面量形式:
//简单类型数组
var value = [25,"hi",true]
//复杂类型数组
[{
"title": "Pro",
"author": "Qianwe",
"edition": 3,
"year": 2100
},
{
"title": "Pro",
"author": "Qianwe",
"edition": 4,
"year": 2100
},
{
"title": "Pro",
"author": "Qianwe",
"edition": 2,
"year": 2100
}
]
var book=[{
"title": "Pro",
"author": "Qianwe",
"edition": 3,
"year": 2100
},
{
"title": "Pro1",
"author": "Qianwe",
"edition": 4,
"year": 2100
},
{
"title": "Pro2",
"author": "Qianwe",
"edition": 2,
"year": 2100
}
]
//------------------------------------------------------------
books[2].title //pro2
json对象与json字符串转换
json对象-》json字符串 JSON.stringify
var jsonText = JSON.stringify(books);
var books = {
"title": "Pro",
"author": "Qianwe",
"edition": 4,
"year": 2100
};
var jsonText = JSON.stringify(books);
console.log(jsonText) //{"title":"Pro","author":"Qianwe","edition":4,"year":2100}
console.log(typeof jsonText) //string
json字符串-》json对象 JSON.parse
JSON.parse(jsonText)
var books = {
"title": "Pro",
"author": "Qianwe",
"edition": 4,
"year": 2100
};
var jsonText = JSON.stringify(books);
console.log(jsonText) //{"title":"Pro","author":"Qianwe","edition":4,"year":2100}
console.log(typeof jsonText) //string
var parseText = JSON.parse(jsonText);
console.log(parseText)
/*
{title: "Pro", author: "Qianwe", edition: 4, year: 2100}
author
:
"Qianwe"
edition
:
4
title
:
"Pro"
year
:
2100
__proto__
:
Object
*/
console.log(typeof parseText) //object
JSON 文件的文件类型是 ".json"
JSON 文本的 MIME 类型是 "application/json"
网友评论