python str dic json 字串和檔案轉化為字典
阿新 • • 發佈:2018-11-11
python 字串和字典相互轉換
1,python資料轉換為json資料
#!/usr/local/bin/python3
# coding:utf-8
import json
data = '{"name": "ni", "city": "tt", "id" : 2256}'
print (data)
print (type(data))
#print (data['name'])
json_str = json.loads(data)
print (type(json_str))
print (json_str['name'])
print ("測試")
{"name": "ni", "city": "tt", "id" : 2256}
<class 'str'>
<class 'dict'>
ni
測試
- 報錯,data裡面字串必須使用雙引號
Expecting property name enclosed in double quotes
2,json.dumps() 和 json.loads() 編碼和解碼JSON資料
json.dumps():將python中的字典轉換為字串
json.loads(): 將字串轉換為字典
#!/usr/local/bin/python3
# coding:utf-8
import json
data = {
'name' : 'ni',
'city' : 'tt',
'id' : 2256
}
print ("data : " , data)
print ("type data : " , type(data))
print ("data['name']: " , data['name'])
data_str = json.dumps(data)
print ("data_str type : " , type(data_str))
print ("data_str : " , data_str)
data_json = json.loads(data_str)
print ("type data_json : " , type(data_json))
print ("data_json['name'] : ", data_json['name'])
print ("測試")
data : {'name': 'ni', 'city': 'tt', 'id': 2256}
type data : <class 'dict'>
data['name']: ni
data_str type : <class 'str'>
data_str : {"name": "ni", "city": "tt", "id": 2256}
type data_json : <class 'dict'>
data_json['name'] : ni
測試
3,檔案轉換為字典
$ cat data
{
"name" : "ni",
"city" : "tt",
"id" : 2256
}
$
#!/usr/local/bin/python3
# coding:utf-8
import json
file = "/root/data"
print ("file type : " , type(file))
file_open = open(file , 'r')
print ("file_open type : " , type(file_open))
file_read = file_open.read()
print ("file_read type : " , type(file_read))
data = json.loads(file_read)
print ("data type : " , type(data))
print ("data['name'] : " , data['name'])
print ("測試")
file type : <class 'str'>
file_open type : <class '_io.TextIOWrapper'>
file_read type : <class 'str'>
data type : <class 'dict'>
data['name'] : ni
測試
#!/usr/local/bin/python3
# coding:utf-8
import json
file = "/Users/y50/data"
with open (file , 'r') as f:
file_read = f.read()
data = json.loads(file_read)
print (data['name'])
print ("測試")
ni
測試
參考: