Depending on the API, sometimes we need to change the structure of the dictionary before we convert it to JSON. For example, assume that we have the following dictionary
.
my_dict = {'variant_id' : [1,2,3], 'impressions' : [100, 120, 90]} my_dict
Output:
{'variant_id': [1, 2, 3], 'impressions': [100, 120, 90]}
Let’s say that we want to generate a JSON file of the following form:
[{'variant_id': 1, 'impressions': 100}, {'variant_id': 2, 'impressions': 120}, {'variant_id': 3, 'impressions': 90}]
We can generate this file as follows:
import json my_json = [{"variant_id":int(i), "impressions":j} for i,j in zip(my_dict['variant_id'],my_dict['impressions'])] my_json = json.dumps(my_json) my_json
Output:
'[{"variant_id": 1, "impressions": 100}, {"variant_id": 2, "impressions": 120}, {"variant_id": 3, "impressions": 90}]'
Finally, if we want to convert the JSON to Pandas data frame:
import pandas as pd pd.json_normalize(json.loads(my_json))