Thabra
Thabra

Reputation: 337

Cannot transform a Json into pandas dataframe

I have a json file like that:

{
    "info": [
        {
            "product": "ABC",
            "email-adr": "[email protected]",
            "Gender": "M",
            "Name": "João",
            "id": "1069",
            "mobile": "iOS | 9.1",
            "client": " "
        },

I tried to:

data2 = pd.read_json('file.json', encoding=str)

but got a df with a single column:

                      info
0  {u'id':u'1069',u'client'..    

What is the best way to read this json file to a pandas df?

Upvotes: 2

Views: 93

Answers (1)

Oliver
Oliver

Reputation: 90

You have to pass as argument only the inner object:

import json

z="""{
"info":
[
{"product": "ABC", "email-adr": "[email protected]", "Gender": "M", "Name": "João", "id": "1069", "mobile": "iOS | 9.1", "client": " " }]}"""
>>> pd.DataFrame(json.loads(z)['info'])

  Gender  Name client        email-adr    id     mobile product
0      M  João         [email protected]  1069  iOS | 9.1     ABC

To load a json file:

with open("file.json", "r") as f:
  data = json.load(f)

Then you can do

pd.DataFrame(data['info'])

Upvotes: 1

Related Questions