1

I am trying to import a sample json file into pandas dataframe

I already tried ValueError: Expected object or value when reading json as pandas dataframe

Error :

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-bd3924a4e6a1> in <module>()
      1 # working with json
      2 import pandas as pd
----> 3 df = pd.read_json("/content/drive/MyDrive/Datasets/sample3.json", lines=True)
      4 df.head()

6 frames
/usr/local/lib/python3.7/dist-packages/pandas/io/json/_json.py in _parse_no_numpy(self)
   1117         if orient == "columns":
   1118             self.obj = DataFrame(
-> 1119                 loads(json, precise_float=self.precise_float), dtype=None
   1120             )
   1121         elif orient == "split":

ValueError: Expected object or value

1 Try :

# working with json
import pandas as pd
df = pd.read_json("/content/drive/MyDrive/Datasets/sample3.json") 
#df = pd.read_json("/content/drive/MyDrive/Datasets/sample3.json", lines=True)  #also tried 
#df = pd.read_json("/content/drive/MyDrive/Datasets/sample3.json", lines=True, orient='records') # also tried 
#df = pd.read_json("/content/drive/MyDrive/Datasets/sample3.json", orient=str) # also tried 
df.head()

Json File :

[
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    },
    {
        color: "blue",
        value: "#00f"
    },
    {
        color: "cyan",
        value: "#0ff"
    },
    {
        color: "magenta",
        value: "#f0f"
    },
    {
        color: "yellow",
        value: "#ff0"
    },
    {
        color: "black",
        value: "#000"
    }
]
Juned Ansari
  • 5,035
  • 7
  • 56
  • 89

2 Answers2

3

That is not valid JSON.

JSON must have its objects' keys quoted with double quotes, like so:

{
    "color": "red",
    "value": "#f00"
}
marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
3

This is actually just a JSON problem. If I create your JSON file in my IDE, I immediately get formatting errors because the file is not properly encoded. It says:

property keys must be doublequoted

If I make the replacements

[
    {
        "color": "red",
        "value": "#f00"
    },
    {
        "color": "green",
        "value": "#0f0"
    }
]

I can now use

df = pd.read_json("file.json") 
print(df)

to get

   color value
0    red  #f00
1  green  #0f0
Kraigolas
  • 5,121
  • 3
  • 12
  • 37