How can I loop over a json array that looks like the one below, using python?
{
"insights": {
"data": [
{
"name": "page_impressions",
"period": "day",
"values": [
{
"value": 14,
"end_time": "2022-05-16T07:00:00+0000"
},
{
"value": 17,
"end_time": "2022-05-17T07:00:00+0000"
}
],
"title": "Daily Total Impressions",
"description": "Daily: The number of times any content from your Page or about your Page entered a person's screen. This includes posts, stories, ads, as well other content or information on your Page. (Total Count)",
"id": "/insights/page_impressions/day"
},
{
"name": "page_impressions",
"period": "week",
"values": [
{
"value": 14,
"end_time": "2022-05-16T07:00:00+0000"
},
{
"value": 31,
"end_time": "2022-05-17T07:00:00+0000"
}
],
"title": "Weekly Total Impressions",
"description": "Weekly: The number of times any content from your Page or about your Page entered a person's screen. This includes posts, stories, ads, as well other content or information on your Page. (Total Count)",
"id": "/insights/page_impressions/week"
},
{
"name": "page_impressions",
"period": "days_28",
"values": [
{
"value": 14,
"end_time": "2022-05-16T07:00:00+0000"
},
{
"value": 31,
"end_time": "2022-05-17T07:00:00+0000"
}
],
"title": "28 Days Total Impressions",
"description": "28 Days: The number of times any content from your Page or about your Page entered a person's screen. This includes posts, stories, ads, as well other content or information on your Page. (Total Count)",
"id": "/insights/page_impressions/days_28"
}
]
I know how to loop over individual items:
values = profile['insights']['data'][0]['values'][0]
But this isn’t a feasible solution considering that I need to loop over every item and display the output and store it. Any help would be appreciated.
2
Answers
How to iterate the json, this is one way you could do it:
Data:
Code:
Result:
If you need to unpack it even further:
Result:
There are 2 ways to do it:
Option (1) fixed schema
Option (2) for any schema
Both options will output:
After that you could place them in a DataFrame
Output