Python | 将json数据转换成字典
2019-02-16 本文已影响1人
Quora文选
要求:把下面的数据转换成字典:
2019年02月15日 21:08:20
i:I love seajay
from:AUTO
to:AUTO
smartresult:dict
client:fanyideskweb
salt:15483356026163
sign:0e6fc7b099ab52173b750e4f1fe2e967
ts:1548335602616
bv:563490a3a59c96d89a5868bde7ab81c1
doctype:json
version:2.1
keyfrom:fanyi.web
action:FY_BY_CLICKBUTTION
typoResult:false
解决:
- 将以上文件存在txt文件中,并命名为:原始数据.txt
- 利用python来实现json数据的转换:
data = {}
filename = "原始数据.txt"
with open(filename) as f:
lines = f.readlines()
for line in lines:
key = line.split(":")[0]
value = line.split(":")[1].strip()
data[key] = value
print("data['%s'] = '%s'" % (key, value))
print(data)
也可以这样写:
data = {}
filename = "原始数据.txt"
with open(filename) as f:
lines = f.readlines()
for line in lines:
key = line[: line.index(':')]
value = line[line.index(':') + 1:].rstrip()
data[key] = value
print("data['%s'] = '%s'" % (key, value))
print(data)
输出结果为:
>>> %Run 'json转字典.py'
data['i'] = 'I love seajay'
data['from'] = 'AUTO'
data['to'] = 'AUTO'
data['smartresult'] = 'dict'
data['client'] = 'fanyideskweb'
data['salt'] = '15483356026163'
data['sign'] = '0e6fc7b099ab52173b750e4f1fe2e967'
data['ts'] = '1548335602616'
data['bv'] = '563490a3a59c96d89a5868bde7ab81c1'
data['doctype'] = 'json'
data['version'] = '2.1'
data['keyfrom'] = 'fanyi.web'
data['action'] = 'FY_BY_CLICKBUTTION'
data['typoResult'] = 'false'
{'i': 'I love seajay', 'from': 'AUTO', 'to': 'AUTO', 'smartresult': 'dict', 'client': 'fanyideskweb', 'salt': '15483356026163', 'sign': '0e6fc7b099ab52173b750e4f1fe2e967', 'ts': '1548335602616', 'bv': '563490a3a59c96d89a5868bde7ab81c1', 'doctype': 'json', 'version': '2.1', 'keyfrom': 'fanyi.web', 'action': 'FY_BY_CLICKBUTTION', 'typoResult': 'false'}