[英]How can I extract the inner string elements from a json using python?
我有这个奇怪的原始 JSON 输入:
{
"URL_IN": "http://localhost/",
"DownloadData": "{\"data\":[{samples:[{t:1586826385724,v:5.000e+000,l:0,s:-1,V:-1},{t:1587576460460,v:0.000e+000,l:0,s:-1,V:-1}]}]}"
}
我想使用 Python 从样本中访问和提取内部元素,例如t
、 v
。
您可以先使用regex
清理 json 。 为了清理,我将 json 分成两部分url_data and download_data
。
第一步从download_data
中删除不必要的双引号,这个正则表达式re.sub('"', '', data[data.index(',') + 1:])
删除了双引号。
接下来使用正则表达式为单词添加双引号re.sub("(\w+):", r'"\1":', download_data)
这将在 json 中的所有单词周围添加双引号。
import re
import json
data = '{"URL_IN": "http://localhost/","DownloadData": "{\"data\":[{samples:[{t:1586826385724,v:5.000e+000,l:0,s:-1,V:-1},{t:1587576460460,v:0.000e+000,l:0,s:-1,V:-1}]}]}"}'
url_data = data[:data.index(',') + 1]
download_data = re.sub('"', '', data[data.index(',') + 1 :])
data = url_data + re.sub("(\w+):", r'"\1":', download_data)
data = json.loads(data)
res = [(x['t'], x['v']) for x in data['DownloadData']['data'][0]['samples']]
t, v = map(list, zip(*res))
print(t, v)
Output:
[1586826385724, 1587576460460] [5.0, 0.0]
这里我看到的主要问题是DownloadData
中的值不是 json 格式,因此您需要将其设为 json。
代码
a={ "URL_IN": "http://localhost/", "DownloadData": "{\"data\":[{samples:[{t:1586826385724,v:5.000e+000,l:0,s:-1,V:-1},{t:1587576460460,v:0.000e+000,l:0,s:-1,V:-1}]}]}" }
i = a['DownloadData']
#converting string to json
i = i.replace("{",'{"').replace("}",'"}').replace(":",'":"').replace(",",'","')
i = i.replace("\"\"",'\"').replace("\"[",'[').replace("\"]",']').replace("\"{",'{').replace("\"}",'}')
i = i.replace("}]}]}","\"}]}]}")
i = i.replace("}\"","\"}")
final_dictionary = json.loads(i)
for k in final_dictionary['data'][0]['samples']:
print("t = ",k['t'])
print("v = ",k['v'])
print("l = ",k['l'])
print("s = ",k['s'])
print("V = ",k['V'])
print("###############")
Output
t = 1586826385724
v = 5.000e+000
l = 0
s = -1
V = -1
###############
t = 1587576460460
v = 0.000e+000
l = 0
s = -1
V = -1
###############
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.