程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python JSON

編輯:Python

JSON (JavaScript Object Notation) Is a lightweight data exchange format .

If you don't already know JSON, You can read our JSON course .

Python3 Can be used in json Module to JSON Data encoding and decoding , It contains two functions :

json.dumps(): Code the data .
json.loads(): Decode the data .


stay json In the process of encoding and decoding ,Python The original type of json The types will switch to each other , The specific transformation contrast is as follows :

Python Encoded as JSON Type conversion correspondence table :
Python    JSON
dict    object
list, tuple    array
str    string
int, float, int- & float-derived Enums    number
True    true
False    false
None    null
JSON Decoding for Python Type conversion correspondence table :
JSON    Python
object    dict
array    list
string    str
number (int)    int
number (real)    float
true    True
false    False
null    None
json.dumps And json.loads example
The following example demonstrates Python The data structure is converted to JSON:

example (Python 3.0+)
#!/usr/bin/python3 import json # Python Dictionary type to JSON object data = { 'no' : 1, 'name' : 'Runoob', 'url' : 'http://www.runoob.com' } json_str = json.dumps(data) print ("Python Raw data :", repr(data)) print ("JSON object :", json_str)

The result of executing the above code is :

Python Raw data : {'url': 'http://www.runoob.com', 'no': 1, 'name': 'Runoob'}
JSON object : {"url": "http://www.runoob.com", "no": 1, "name": "Runoob"}
The output shows that , Simple types are encoded followed by their original repr() The output is very similar .

Then the above example , We can put a JSON The encoded string is converted back to a Python data structure :

example (Python 3.0+)
#!/usr/bin/python3 import json # Python Dictionary type to JSON object data1 = { 'no' : 1, 'name' : 'Runoob', 'url' : 'http://www.runoob.com' } json_str = json.dumps(data1) print ("Python Raw data :", repr(data1)) print ("JSON object :", json_str) # take JSON Object to Python Dictionaries data2 = json.loads(json_str) print ("data2['name']: ", data2['name']) print ("data2['url']: ", data2['url'])

The result of executing the above code is :

Python Raw data : {'name': 'Runoob', 'no': 1, 'url': 'http://www.runoob.com'}
JSON object : {"name": "Runoob", "no": 1, "url": "http://www.runoob.com"}
data2['name']:  Runoob
data2['url']:  http://www.runoob.com
If you're dealing with files instead of strings , You can use json.dump() and json.load() To code and decode JSON data . for example :

example (Python 3.0+)
# write in JSON data with open('data.json', 'w') as f: json.dump(data, f) # Reading data with open('data.json', 'r') as f: data = json.load(f)

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved