json(javascript object notation)(rfc 4627)是目前web数据交换的事实标准。本文记叙json的格式,以及javascript与python的json库使用实践。
json语法可以表述以下三种类型的值:
简单值 使用javascript相同的语法,可以表示字符串、数值、布尔值、null、(没有undefined)。例如<code>5</code>,<code>"hello world"</code>,<code>null</code>,都属于简单值。
对象 复杂数据类型,一组无序的键值对,每个键值对的键必须是双引号括起的字符串,值可以是简单值也可以是复杂数据类型。例如
<code>{</code>
<code>"name": "haha"</code>
<code>"age": 74</code>
<code>}</code>
数组 复杂数据类型,表示有序的值的列表,可通过数值索引访问,数组的值可以是简单值也可以是复杂数据类型,且同一数组内可以同时出现任意类型的值。例如
<code>["a", 2, {"b":3},[4, 5, 6] ]</code>
json对象中的键应当是独一无二的,但在json表示中没有强制这一点,通常的做法都是取最后一次出现的value作为重复key的值。
rfc规定了json必须使用utf-8,utf-16,utf-32中的编码来表示。一般使用utf-8编码。在json的字符串中最好不要使用unicode字面值,使用\uxxxx的形式表示能有效降低乱码的可能性。
rfc禁止json的字符表示前出现bom标记。
rfc没有明确禁止json的string中出现非法unicode字节序列,比如“unpaired utf-16 surrogates”。
早期的json解析器基本上就是使用<code>eval()</code>函数进行的。
但这样做存在安全隐患,所以在浏览器或者node中定义有全局模块<code>json</code>。
<code>json.stringify(value[, replacer[, space]])</code>
<code>json.stringify</code>方法会忽略所有原型成员,以及所有值为<code>undefined</code>的属性。
该方法可以指定两个可选参数:过滤器函数与缩进字符。
if you return a <code>number</code>, the string corresponding to that number is used as the value for the property when added to the json string.
if you return a <code>string</code>, that string is used as the property’s value when adding it to the json string.
if you return a <code>boolean</code>, “true” or “false” is used as the property’s value, as appropriate, when adding it to the json string.
if you return <code>any other object</code>, the object is recursively stringified into the json string, calling the replacer function on each property, unless the object is a function, in which case nothing is added to the json string.
if you return <code>undefined</code>, the property is not included in the output json string.
<code>function replacer(key, value) {</code>
<code>if (typeof value === "string") {</code>
<code>return undefined;</code>
<code>return value;</code>
<code></code>
<code>var foo = {foundation: "mozilla", model: "box", week: 45, transport: "car", month: 7};</code>
<code>var jsonstring = json.stringify(foo, replacer);</code>
可以在过滤器函数中滤除不必要的属性
如果指定为数字,使用空格作为indent,最大为10.
也可以指定为其他字符。
<code>json.stringify({ uno: 1, dos: 2 }, null, '\t');</code>
<code>// returns the string:</code>
<code>// '{</code>
<code>// "uno": 1,</code>
<code>// "dos": 2</code>
<code>// }'</code>
<code>json.stringify</code>的解析顺序如下
如果存在<code>tojson</code>方法且能通过该方法取得有效值,调用该方法,否则返回对象本身。
如果提供第二个参数:函数过滤器,使用它,传入第一步的返回值。
对第二步返回的每个值进行相应的序列化。
执行格式化。
<code>var obj = {</code>
<code>foo: 'foo',</code>
<code>tojson: function() {</code>
<code>return 'bar';</code>
<code>};</code>
<code>json.stringify(obj); // '"bar"'</code>
<code>json.stringify({ x: obj }); // '{"x":"bar"}'</code>
<code>json.parse(text[, reviver])</code>
从字符串中解析json,可以选定一个reviver函数作为hooki。
<code>json.parse('{}'); // {}</code>
<code>json.parse('true'); // true</code>
<code>json.parse('"foo"'); // "foo"</code>
<code>json.parse('[1, 5, "false"]'); // [1, 5, "false"]</code>
<code>json.parse('null'); // null</code>
<code>json.parse('{"p": 5}', function(k, v) {</code>
<code>if (typeof v === 'number') {</code>
<code>return v * 2; // return v * 2 for numbers</code>
<code>return v; // return everything else unchanged</code>
<code>});</code>
python的json模块基本与js类似。
json
python
object
dict
array
list
string
unicode
number
(int) int, long
numbe
(real) float
true
false
null
none
<code>>>> import json</code>
<code>>>> json.dumps(['foo', {'bar': ('baz', none, 1.0, 2)}])</code>
<code>'["foo", {"bar": ["baz", null, 1.0, 2]}]'</code>
<code>>>> print json.dumps("\"foo\bar")</code>
<code>"\"foo\bar"</code>
<code>>>> print json.dumps(u'\u1234')</code>
<code>"\u1234"</code>
<code>>>> print json.dumps('\\')</code>
<code>"\\"</code>
<code>>>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=true)</code>
<code>{"a": 0, "b": 0, "c": 0}</code>
<code>>>> print json.dumps(none)'</code>
<code>null</code>
其格式可以通过indent参数控制。
<code>>>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))</code>
<code>'[1,2,3,{"4":5,"6":7}]'</code>
<code>>>> print json.dumps({'4': 5, '6': 7}, sort_keys=true,</code>
<code>... indent=4, separators=(',', ': '))</code>
<code>"4": 5,</code>
<code>"6": 7</code>
<code>>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')</code>
<code>[u'foo', {u'bar': [u'baz', none, 1.0, 2]}]</code>
<code>>>> json.loads('"\\"foo\\bar"')</code>
<code>u'"foo\x08ar'</code>
<code>$ echo '{"json":"obj"}' | python -mjson.tool</code>
<code>"json": "obj"</code>