Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: json normalize "String indices must be integers" error

Tags:

I am getting a type error as "TypeError: string indices must be integers" in the following code.

import pandas as pd 
import json
from pandas.io.json import json_normalize

full_json_df = pd.read_json('data/world_bank_projects.json')
json_nor = json_normalize(full_json_df, 'mjtheme_namecode')
json_nor.groupby('name')['code'].count().sort_values(ascending=False).head(10)
Output:
TypeError                                 
Traceback (most recent call last)
<ipython-input-28-9401e8bf5427> in <module>()
      1 # Find the top 10 major project themes (using column 'mjtheme_namecode')
      2 
----> 3 json_nor = json_normalize(full_json_df, 'mjtheme_namecode')
      4 #json_nor.groupby('name')['code'].count().sort_values(ascending = False).head(10)
TypeError: string indices must be integers
like image 822
Sheema Murugesh Babu Avatar asked Apr 16 '19 14:04

Sheema Murugesh Babu


People also ask

How do I fix error string indices must be integers in python?

You cannot access a value in a string using another string. To solve TypeError: string indices must be integers; we should reference our dictionary instead of “ele“. We can access elements in our dictionary using a string. This is because dictionary keys can be strings.

How do you resolve string indices must be integers?

1 comment. String indices must be integers. This means that when you're accessing an iterable object like a string, you must do it using a numerical value. If you are accessing items from a dictionary, make sure that you are accessing the dictionary itself and not a key in the dictionary.

How do you convert a string to a JSON object in Python?

you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.

What is JSON normalize?

A simple way to traverse datasets based on JSON API specification. Normalize is a lightweight javascript library with simple and powerful api.


1 Answers

According to pandas documentation, for data argument of the method json_normalize :

data : dict or list of dicts Unserialized JSON objects

In above, pd.read_json returns dataframe. So, you can try converting dataframe to dictionary using .to_dict(). There are various options for using to_dict() as well.

May be something like below:

json_normalize(full_json_df.to_dict(), ......)
like image 111
student Avatar answered Oct 04 '22 19:10

student