I have JSON response in a <class 'dict'>
. I want to iterate over the JSON response and form a table view. Below is the sample JSON response.
{'ResultSet': {'Rows': [{'Data': [{'VarCharValue': 'cnt'}, {'VarCharValue': 'id'}, {'VarCharValue': 'val'}]}, {'Data': [{'VarCharValue': '2000'}, {'VarCharValue': '1234'}, {'VarCharValue': 'ABC'}]},{'Data': [{'VarCharValue': '3000'}, {'VarCharValue': '5678'}, {'VarCharValue': 'DEF'}]}]}}
Expected Output format:
cnt id val
2000 1234 ABC
3000 5678 DEF
There can only one row of data or there can be multiple rows of data for the column set (For provided sample data two rows are there).
I am not sure if you are using pandas
but you can easily parse your response
dict into a pandas.DataFrame
with the following code
import pandas as pd
pd.DataFrame([[entr['VarCharValue'] for entr in r['Data']] for r in response['ResultSet']['Rows'][1:]],
columns = [r['VarCharValue'] for r in response['ResultSet']['Rows'][0]['Data']])
I assume you want to use Pandas. Since pd.DataFrame
accepts a list of dictionaries directly, you can restructure your input dictionary D
as a list of dictionaries:
cols = [next(iter(i.values())) for i in D['ResultSet']['Rows'][0]['Data']]
d = [{col: j['VarCharValue'] for col, j in zip(cols, i['Data'])}
for i in D['ResultSet']['Rows'][1:]]
df = pd.DataFrame(d)
print(df)
cnt id val
0 2000 1234 ABC
1 3000 5678 DEF
You will probably want to convert at least the cnt
series to numeric:
df['cnt'] = pd.to_numeric(df['cnt'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.