Trabalhando com Dados JSON
Agora que sabemos como importar corretamente o módulo JSON, vamos explorar como usá-lo para operações JSON comuns.
Criando um Exemplo Completo de JSON
Crie um novo arquivo chamado json_operations.py com o seguinte conteúdo:
## Complete example of working with JSON in Python
import json
## 1. Converting Python object to JSON string (serialization)
user = {
"name": "Charlie",
"age": 28,
"is_student": False,
"courses": ["Python", "Data Science", "Web Development"],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
## Convert Python dictionary to JSON string
json_string = json.dumps(user, indent=2)
print("JSON string created from Python object:")
print(json_string)
print("\n" + "-"*50 + "\n")
## 2. Parse JSON string to Python object (deserialization)
parsed_user = json.loads(json_string)
print("Python object created from JSON string:")
print("Name:", parsed_user["name"])
print("Age:", parsed_user["age"])
print("Courses:", parsed_user["courses"])
print("City:", parsed_user["address"]["city"])
print("\n" + "-"*50 + "\n")
## 3. Writing JSON to a file
with open("/home/labex/project/user_data.json", "w") as json_file:
json.dump(user, json_file, indent=2)
print("JSON data written to user_data.json")
## 4. Reading JSON from a file
with open("/home/labex/project/user_data.json", "r") as json_file:
loaded_user = json.load(json_file)
print("JSON data loaded from file. User name:", loaded_user["name"])
Este script demonstra quatro operações JSON comuns:
- Converter um objeto Python em uma string JSON usando
json.dumps()
- Analisar uma string JSON em um objeto Python usando
json.loads()
- Escrever dados JSON em um arquivo usando
json.dump()
- Ler dados JSON de um arquivo usando
json.load()
Execute o script:
python3 /home/labex/project/json_operations.py
Você deve ver uma saída semelhante a:
JSON string created from Python object:
{
"name": "Charlie",
"age": 28,
"is_student": false,
"courses": [
"Python",
"Data Science",
"Web Development"
],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
--------------------------------------------------
Python object created from JSON string:
Name: Charlie
Age: 28
Courses: ['Python', 'Data Science', 'Web Development']
City: Boston
--------------------------------------------------
JSON data written to user_data.json
JSON data loaded from file. User name: Charlie
O script também criou um arquivo chamado user_data.json. Vamos olhar seu conteúdo:
cat /home/labex/project/user_data.json
Você deve ver os dados JSON formatados com a indentação adequada:
{
"name": "Charlie",
"age": 28,
"is_student": false,
"courses": ["Python", "Data Science", "Web Development"],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
Você agora aprendeu com sucesso como trabalhar com dados JSON em Python, incluindo como evitar o erro NameError: name 'json' is not defined importando corretamente o módulo.