I'm trying to parse this JSON using pandas and getting this particular error:
{
"tables": [
{
"name": "PrimaryResult",
"columns": [
{
"name": "ApiId",
"type": "string"
},
{
"name": "count_",
"type": "long"
}
],
"rows": [
[
"test 1",
654321
],
[
"test 2",
32564
],
[
"test 3",
185262
]
]
}
]
}
analytics_data = response_analytics.text
json_dict = json.loads(analytics_data)
df = pd.DataFrame.from_dict(json_dict["tables"])
cols_to_keep = ["ApiId", "count_"]
df_final = df[cols_to_keep]
df_final = df_final.rename(columns={"ApiId": "API Name", "count_": "Total requests"})
print(
tabulate(
df_final, showindex=False, headers=df_final, tablefmt="psql", numalign="left"
)
)
Error:
Traceback (most recent call last):
File "C:\Users\test\te.py", line 93, in df_final = df[cols_to_keep]
File "C:\Users\test\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\core\frame.py", line 3461, in getitem indexer = self.loc._get_listlike_indexer(key, axis=1)1
File "C:\Users\test\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\core\indexing.py", line 1314, in _get_listlike_indexer self._validate_read_indexer(keyarr, indexer, axis)
File "C:\Users\test\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\core\indexing.py", line 1374, in validate_read_indexer raise KeyError(f"None of [{key}] are in the [{axis_name}]") KeyError: "None of [Index(['ApiId', 'count'], dtype='object')] are in the [columns]"
My goal is to create something like this:
API Name Total requests
---------------------------------- ---------------------
test 1 654321
test 2 32564
test 3 185262
How can I convert this JSON schema to a table? The data is exported using a REST API
Print results:
print(tabulate(df, showindex=False, headers=df, tablefmt='psql', numalign="left"))

json_dict = json.loads(text_data)should it betext_dataoranalytics_data?analytics_date. Updated the code and the error. Thanks @Owenndf.columnsto see what are the column name that exists in the dataframe, and you could userename()to rename those columns into the ones you want.df = pd.DataFrame(data=json_dict["tables"][0]["rows"], columns=[r["name"] for r in json_dict["tables"][0]["columns"]])?