python version : 3.4.4
測試資料:
import json
aa =
bb = [ ,, ]
json模組提供的函式 json.dumps() 和 json.loads()
輸出:
>>> print(bb)
[, , ]
>>>
>>> data=json.dumps(bb)
>>> print(data)
[, , ]
>>>
>>> load = json.loads(data)
>>> print(load)
[, , ]
>>>
排序:
>>> data = json.dumps(bb,sort_keys=true)
>>> print(data)
[, , ]
>>>
格式化輸出:
>>> data = json.dumps(bb,indent=4)
>>> print(data)
[ ,
,]>>>
輸出某行資料:
>>> print(bb[0])
>>>
>>> print(bb[1])
>>>
>>> print(bb[2])
>>>
輸出某行資料某個值:
>>> print(bb[1]["name"])
qq>>>
>>> print(bb[1]["age"])
20>>>
遍歷/迴圈 json :
>>> bb = [ ,, ]
>>>
>>> for item in bb:
... print(item,item["name"])
... mm
qq hh
>>>
>>> for i in range(len(bb)):
... print(i,bb[i],bb[i]["name"])
...0 mm
1 qq
2 hh
>>>
>>> for i,item in enumerate(bb):
... print(i,item,item["name"])
...0 mm
1 qq
2 hh
>>>
>>> for item in bb:
... print("name=%s,age=%s,age=%f"%(item["name"],item["age"],item["age"]))
...name=mm,age=10,age=10.000000
name=qq,age=20,age=20.000000
name=hh,age=50,age=50.000000
>>>
>>> for item in bb:
... print("my name is ".format(item["name"]))
...my name is mm
my name is qq
my name is hh
>>>
>>> for i,j in bb:
... print("name: , age: ".format(i,j))
...name: name, age: age
name: name, age: age
name: name, age: age
>>>
json 轉 python 資料格式定義:
+---------------+-------------------+
| json | python |
+***************+***************====+
| object | dict |
+---------------+-------------------+
| array | list |
+---------------+-------------------+
| string | str |
+---------------+-------------------+
| number (int) | int |
+---------------+-------------------+
| number (real) | float |
+---------------+-------------------+
| true | true |
+---------------+-------------------+
| false | false |
+---------------+-------------------+
| null | none |
+---------------+-------------------+
python 轉 json 資料格式定義:
+-------------------+---------------+
| python | json |
+***************====+***************+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str | string |
+-------------------+---------------+
| int, float | number |
+-------------------+---------------+
| true | true |
+-------------------+---------------+
| false | false |
+-------------------+---------------+
| none | null |
+-------------------+---------------+
更多參考:json encoder and decoder
help("json")
Python Json操作封裝的基本實現
usr bin env python3 coding utf 8 name jsonconfig version 0.0.1 packages author singebogo author email singbogo 163.com date 20180427 import json,demjs...
python json轉化操作
usr bin python coding utf 8 import json import sys import os 重要函式 編碼 把乙個python物件編碼轉換成json字串 json.dumps 解碼 把json格式字串解碼轉換成python物件 json.loads def test00...
Python JSON的基本使用
json.loads 用於解碼json資料,該函式返回python欄位的資料型別。loads 方法 import json jsondata res json.loads jsondata print res print type res loads 傳的是字串 注意 檔案裡只能寫字串,但是可以把字...