JSON获取请求的故障排除格式 [英] Troubleshooting format of JSON get request
问题描述
我在尝试将get请求响应转换为所需格式时遇到问题. JSON响应的结构稍微复杂一些,我很难将其转换为正确的格式.
I'm running into an issue with trying to convert a get request response into my desired format. The structure of the JSON response is a little more complicated and I'm having trouble with getting it into the right format.
这是我的代码,用于将json脚本转换为熊猫数据框:
Here's my code for converting the json script into a pandas dataframe:
data = pd.DataFrame.from_dict(resp_isrc.json())
data.head()
下面是我得到的JSON结构:
This is JSON structure that I am getting is below:
{"country":"US",
"artist_name":"Frank Ocean",
"title_name":"Provider",
"release_date":"2017-08-25",
"core_genre":"R&B/Hip-Hop",
"metrics":[{"name":"ISRC w/SES On-Demand",
"value":[{"name":"tp","value":2810},
{"name":"lp","value":2450},
{"name":"ytd","value":2740},
{"name":"atd","value":554267}]},
推荐答案
可能需要一些预处理才能实现所需的功能.对于来自请求的json结果,这是相当典型的.在某些情况下,可以使用更通用的方法.但是在这里,由于结构非常简单,因此指标可以很容易地展平.
A bit of preprocessing may be needed to achieve what you want. This is fairly typical for json results from requests. In some cases a more general approach may be used. But here, since the structure is fairly simple, metrics can be flattened fairly easily.
def flatten2df(resp_isrc, df=None):
metrics = resp_isrc.pop('metrics')
flattened_json = []
for item in metrics:
metric = item['name']
values = item['value']
new_entry = {entry['name']: entry['value'] for entry in values}
new_entry.update({'metric': metric})
new_entry.update(resp_isrc)
flattened_json.append(new_entry)
new_df = pandas.DataFrame(flattened_json)
if df is None:
return new_df
return df.append(new_df, ignore_index=True)
如果有多个请求,可以将其循环显示
If there are multiple requests, you can loop it over
df = pandas.DataFrame()
for i in lst:
response = requests.get(...)
df = flatten2df(response.json(), df)
更快:
首先将所有展平的结果附加到列表中,然后输入到数据框中.
Faster:
Appends all flattened results to a list first and then input into dataframe.
def flatten2list(resp_isrc, flattened_json):
metrics = resp_isrc.pop('metrics')
for item in metrics:
metric = item['name']
values = item['value']
new_entry = {entry['name']: entry['value'] for entry in values}
new_entry.update({'metric': metric})
new_entry.update(resp_isrc)
flattened_json.append(new_entry)
如果有多个请求,您可以将其循环显示
If there are multiple requests, you can loop it over
results = []
for i in lst:
response = requests.get(...)
flatten2list(response.json(), results)
df = pandas.DataFrame(results)
这篇关于JSON获取请求的故障排除格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!