1

I need to convert this json to pandas dataframe.

"""
{
    "col": [
        {
            "desc": {
                "cont": "Asia",
                "country": "China",
                "Sports": "TT"
            },
            "geo": {
                "col": [
                    [
                        [
                            34,
                            92
                        ],
                     ]
                   ],
                  "c_t": "matic"
            },
            "d_t": "fli"
        }
    ],
    "game": "outdoor"
}

"""

df_output:

col_desc_cont  col_desc_country  col_desc_Sports col_geo_col1  col_geo_co2  col_geo_c_t col_geo_d_t  game
Asia                 China         TT               34          92           matic      fli          outdoor

I want to loop every column value and column header, so that i can get the above result...

1
  • What you can try is import the json into a DF and use DF.explode() is some way. Not sure it will give you exactly what you want but that can be a start. Commented Feb 17, 2022 at 12:09

1 Answer 1

2

That's not actually a valid json (but I fixed it below).

.json_normlaize() is what you are looking for. I'll let you split the geo.col column though.

data = """
{
    "col": [
        {
            "desc": {
                "cont": "Asia",
                "country": "China",
                "Sports": "TT"
            },
            "geo": {
                "col": [
                    [
                        [
                            34,
                            92
                        ]
                     ]
                   ],
                  "c_t": "matic"
            },
            "d_t": "fli"
        }
    ],
    "game": "outdoor"
}

"""

import pandas as pd
import json

jsonData = json.loads(data)
df = pd.json_normalize(jsonData, 
                       record_path=['col'], 
                       meta=['game'] )

Output:

print(df)
   d_t desc.cont desc.country desc.Sports       geo.col geo.c_t     game
0  fli      Asia        China          TT  [[[34, 92]]]   matic  outdoor
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.