16

I have this following JSON array.

[
    {
        "foo"=1
    },
    {
        "foo"=2
    },
    ...
]

I would like to convert it to DataFrame object using pd.read_json() command like below.

df = pd.read_json(my_json) #my_json is JSON array above

However, I got the error, since my_json is a list/array of json. The error is ValueError: Invalid file path or buffer object type: <class 'list'>.

Besides iterating through the list, is there any efficient way to extract/convert the JSON to DataFrame object?

2
  • You're calling read_csv on a list, in your example. Commented May 6, 2018 at 12:55
  • @AmiTavory @thebjorn typo guys. Edited to the correct one, i.e. read_json() Commented May 6, 2018 at 12:58

2 Answers 2

24

Use df = pd.DataFrame(YourList)

Ex:

import pandas as pd

d = [
    {
        "foo":1
    },
    {
        "foo":2
    }
]

df = pd.DataFrame(d)
print(df)

Output:

   foo
0    1
1    2
Sign up to request clarification or add additional context in comments.

Comments

5

There are two problems in your question:

  1. It called to_csv on a list.
  2. The JSON was illegal, as it contained = signs instead of :

This works by me:

import json
import pandas as pd

>>> pd.DataFrame(json.loads("""[
    {
        "foo": 1
    },
    {
        "foo": 2
    }
]"""))

   foo
0    1
1    2

You can also call read_json directly.

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.