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

Teach you how to parse JSON in Python

編輯:Python

SON (JavaScript Object Notation) Is a lightweight data exchange format .Python3 Can be used in json Module to JSON Data encoding and decoding , It mainly includes the following 4 An operation function :

Tips : The so-called class file objects refer to those with read() perhaps write() Object of method , for example ,f = open('a.txt','r'), Among them f Yes read() Method , therefore f It's a class file object .

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 :

JSON Decoding for Python Type conversion correspondence table :

The operation sample :

import json
data = {
'name': 'pengjunlee',
'age': 32,
'vip': True,
'address': {'province': 'GuangDong', 'city': 'ShenZhen'}
}
# take Python Dictionary type to JSON object
json_str = json.dumps(data)
print(json_str) # result {"name": "pengjunlee", "age": 32, "vip": true, "address": {"province": "GuangDong", "city": "ShenZhen"}}
# take JSON Object type is converted to Python Dictionaries
user_dic = json.loads(json_str)
print(user_dic['address']) # result {'province': 'GuangDong', 'city': 'ShenZhen'}
# take Python The dictionary is output directly to a file
with open('pengjunlee.json', 'w', encoding='utf-8') as f:
json.dump(user_dic, f, ensure_ascii=False, indent=4)
# In the class file object JSON The string is converted directly to Python Dictionaries
with open('pengjunlee.json', 'r', encoding='utf-8') as f:
ret_dic = json.load(f)
print(type(ret_dic)) # result <class 'dict'>
print(ret_dic['name']) # result pengjunlee

Be careful : Use eval() Can implement simple string and Python Conversion of types .

user1 =eval('{"name":"pengjunlee"}')
print(user1['name']) # result pengjunlee

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