如何使用python从json提取内部字符串元素?

问题描述 投票:1回答:2

我有这个奇怪的原始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从样本中访问和提取内部元素,例如tv

python json structure
2个回答
1
投票

尝试一下:

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}]}]}"
}'''

download_data = re.sub('"', '', data[data.index(',') + 1 :])
data = data[:data.index(',') + 1] + 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)

输出:

[1586826385724, 1587576460460] [5.0, 0.0]

0
投票

[这里我看到的主要问题是DownloadData中的值不是json格式,因此您需要将其设为json,因为@ komatiraju032确实完成了它,但是我花了很长的路才能实现您想要的。

代码

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("###############")

输出

t =  1586826385724
v =  5.000e+000
l =  0
s =  -1
V =  -1
###############
t =  1587576460460
v =  0.000e+000
l =  0
s =  -1
V =  -1
###############
© www.soinside.com 2019 - 2024. All rights reserved.