Home >Backend Development >Python Tutorial >How to Avoid Errors When Accessing JSON Data from Python Dictionaries

How to Avoid Errors When Accessing JSON Data from Python Dictionaries

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 21:07:02553browse

How to Avoid Errors When Accessing JSON Data from Python Dictionaries

JSON Encoding/Decoding with Python

For seamless data exchange and storage, converting Python dictionaries to JSON (JavaScript Object Notation) is a common requirement. However, unexpected errors can arise when attempting to access JSON data from a dictionary.

Error Encountered:

Consider the following code snippet:

<code class="python">r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
file.write(str(r['rating']))</code>

When attempting to access the 'rating' key from the JSON string, a "TypeError: string indices must be integers, not str" error occurs. This error arises because json.dumps() converts the dictionary 'r' into a string, not an actual JSON object or dictionary.

Correct Approach:

To resolve this issue, utilize the json.loads() method to load the JSON string back into a dictionary. This allows you to access the 'rating' key as follows:

<code class="python">import json

r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
print(loaded_r['rating'])</code>

Understanding the Distinction:

json.dumps() saves a dictionary as a string, while json.loads() retrieves it as a dictionary. Remember to use json.dumps() when serializing data and json.loads() when deserializing it.

The above is the detailed content of How to Avoid Errors When Accessing JSON Data from Python Dictionaries. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn