1

I have a json file that I load into python. I want to take a keyword from the file (which is very big), like country rank or review from info taken from the internet. I tried

json.load('filename.json') 

but I am getting an error:

AttributeError: 'str' object has no attribute 'read.'

What am I doing wrong?

Additionally, how do I select part of a json file if it is very big?

Casey Kuball
  • 7,717
  • 5
  • 38
  • 70

3 Answers3

4

I think you need to open the file then pass that to json load like this

import json
from pprint import pprint

with open('filename.json') as data:    
    output = json.load(data)

pprint(output)
davidejones
  • 1,869
  • 1
  • 16
  • 18
1

Try the following:

import json

json_data_file = open("json_file_path", 'r').read() # r for reading the file
json_data = json.loads(json_data_file)

Access the data using the keys as follows :

json_data['key']
Oogway
  • 33
  • 6
0

json.load() expects the file handle after it has been opened:

with open('filename.json') as datafile:
    data = json.load(datafile)

For example if your json data looked like this:

{
"maps": [
    {
        "id": "blabla",
        "iscategorical": "0"
    },
    {
        "id": "blabla",
        "iscategorical": "0"
    }
],
"masks": {
    "id": "valore"
},
"om_points": "value",
"parameters": {
    "id": "valore"
}
}

To access parts of the data, use:

data["maps"][0]["id"]
data["masks"]["id"]
data["om_points"]

That code can be found in this SO answer: Parsing values from a JSON file using Python?

Community
  • 1
  • 1
sgrg
  • 1,210
  • 9
  • 15
  • I get "AttributeError: 'str' object has no attribute 'read' " when I use this code, i like however the way it is done –  Feb 17 '17 at 17:35
  • ok now error say: " raise JSONDecodeError("Expecting value", s, err.value) from None JSONDecodeError: Expecting value" –  Feb 17 '17 at 17:48
  • and then I try using json.loads() and get " TypeError: the JSON object must be str, not 'TextIOWrapper' " –  Feb 17 '17 at 17:49
  • Are you sure your file filename.json contains data in it? – sgrg Feb 17 '17 at 17:54