Reputation: 23
I'm querying an API that interfaces to MariaDB and this is how I get the data back.
{'TestTable': {'columns': ['Name', 'Id'], 'records': [['Jack', 1], ['Jill', 2]]}}
What I'm trying to achieve is to print the columns before the records like so:
Name: Jack
Id: 1
Name: Jill
Id: 2
I tried to take the data and put the columns and records into different lists and then my idea was to use an if to match the indexes and if match to print the to the format above, but it was the wrong index. Unfortuantely after trying to get it to work after about 5 different ways and 3 hours, I realized I had absolutely no idea what I was doing:
jsonData = json.loads(reqGet.text)
columns = jsonData['TestTable']['columns']
records = jsonData['TestTable']['records']
for idx, val in enumerate(records):
print(idx, val)
Output:
0 ['Jack', 1]
1 ['Jill', 2]
Any thoughts besides "Have you considered digging ditches?", would be great.
Upvotes: 2
Views: 71
Reputation: 18916
You could read it to a pandas dataframe:
import pandas as pd
d = {'TestTable': {'columns': ['Name', 'Id'], 'records': [['Jack', 1], ['Jill', 2]]}}
df = pd.DataFrame(data=d['TestTable']['records'],columns=d['TestTable']['columns'])
df looks like this:
Name Id
0 Jack 1
1 Jill 2
Print it looping through the rows and joining index with value:
for idx,row in df.iterrows():
for item in zip(row.index,row.values):
print(': '.join([str(i) for i in item]))
Result:
Name: Jack
Id: 1
Name: Jill
Id: 2
Upvotes: 0
Reputation: 59274
Using your own code:
jsonData = json.loads(reqGet.text)
columns = jsonData['TestTable']['columns']
records = jsonData['TestTable']['records']
And just changing a little bit your for
loop to iterate through then using the same indexes:
for i in range(len(records)):
data = records[i] # e.g. when i=0, data = ["Jack", 1]
for j in range(len(columns)):
print(col[j], data[j])
Upvotes: 1
Reputation: 61014
d={'TestTable': {'columns': ['Name', 'Id'], 'records': [['Jack', 1], ['Jill', 2]]}}
for record in d['TestTable']['records']:
for col_name, value in zip(d['TestTable']['columns'], record):
print('{}: {}'.format(col_name, value))
will print out
Name: Jack
Id: 1
Name: Jill
Id: 2
Upvotes: 1