A, JSON vs JS objects
1, the difference
the difference | Javascript objects | Json |
---|---|---|
meaning | Instance of an object | A data format (serialization format) |
transmission | Can not transfer | It can be cross-platform transmission, lightweight |
format | 1. bond without the quotes, and single and double quotation marks all rows 2 value may be a function, an object, a string, numeric, boolean, etc. |
1. The key must have double quotes 2. The value can not function / undefined / NaN |
NOTE: 序列化格式
: There are early XML, javascript later based on the birth of more lightweight JSON, and then later there YAML.
For a large number of data sets for scientific use, such as climate, ocean models and satellite data to develop a specific binary serialization standards, such as HDF, netCDF and older GRIB.
2, the sequence of
(1) the sequence of operations
We are serialized -
JSON.stringify()
Deserialization -
JSON.parse()
, (not recommended) eval ()
// 初始化 JS 对象
var obj_origin = {
a: 1,
b: "2",
'c': 3
}
console.log(obj_origin) // { a: 1, b: '2', c: 3 }
// 正序列化
var objStr = JSON.stringify(obj_origin)
console.log(objStr) // {"a":1,"b":"2","c":3}
// 反序列化
var obj = JSON.parse(objStr)
console.log(obj) // { a: 1, b: '2', c: 3 }
var obj2 = eval("(" + objStr + ")")
console.log(obj2) // { a: 1, b: '2', c: 3 }
(2)eval()
First, eval()
the function may be a JS expression is evaluated to a specific object, so the object to parse the string into only one JS effect.
Question one: Why eval () to add parentheses around when parsing?
answer:
. 1, the object is started js "{}" and ending manner, but in the js, it will be mistaken for a block of statements (statement) to process.
2, so with parentheses, in order to put this into a string expression , rather than the statement to execute.
alert(eval("{}")); // return undefined
alert(eval("({})"));// return object[Object]
Question two: Why is not recommended to use eval () it?
answer:
Although the resolving power is stronger than JSON.parse eval, it can not resolve standard JSON string, but the above problem of an example can be seen, eval is unsafe , especially when the data is given to third parties. Therefore, it is recommended to use JSON.parse ( in fact eval JSON.parse bottom is called ).
二、JSON vs JSONB
For more see my previous blog post: Postgres the JSON / JSONB type
三、JSON vs JSONP
For more see my previous blog post: AJAX cross-domain in three ways