Problems trying to access JSON file in Python

Asked

Viewed 668 times

1

Hello, I’m trying to read certain data from a JSON file in Python, but I’m having some problems...

This is the JSON file:

{
   "linguagem":"Python",
   "dados":"JSON"
}

Implementing the JSON file directly into the Python script, it worked, and the Python program looked like this:

import json
test = '{"linguagem": "Python", "dados": "JSON"}'
arquivo = json.loads(test)
print(arquivo [linguagem])

However, I would like to access the JSON file externally. I tried the following command, which did not work:

import json
arquivo = json.loads(TesteJSON.json)
print(arquivo [linguagem])

In the latter case, "Testejson.json" is the name of the JSON file I tried to access.

If anyone can help me, I’d appreciate it!

2 answers

2

To open a file on Python you can use the function open combined with the keyword with.

Behold:

import json

with open('TesteJSON.json', 'r') as f:
    dados = json.loads(f.read())


print(dados['linguagem'])
  • By the method read Python reads files to a string
  • The variable dados receives the value of json.loads, that returns a dict.
  • The dict must have the index accessed through a string as the name of your JSON’s property. The way you did, it could generate an error.

2


The name json.loads has S at the end just to indicate "load String".

json.loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Deserialize s (to str, bytes or bytearray instance containing a JSON Document) to a Python Object using this Conversion table.

What you need is to load from a file. For this there is the function json.load, without the S.

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

Deserialize fp (to .read()-supporting text file or Binary file containing a JSON Document) to a Python Object using this Conversion table.

with open('TesteJSON.json') as stream:
    dados = json.load(stream)

print(dados['linguagem'])

Without context management it could just be:

dados = json.load(open('TesteJSON.json'))
  • I didn’t know that about .load +1

  • 1

    @Wallacemaxters It’s there in the xD documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.