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>