How to Access Data from Converted JSON Dictionaries in Python?

Patricia Arquette
Release: 2024-10-20 21:03:30
Original
826 people have browsed it

How to Access Data from Converted JSON Dictionaries in Python?

Accessing Data in Converted JSON Dictionaries

When attempting to convert a dictionary to JSON, you may encounter difficulties in accessing the data as the converted object is a string.

Consider the following example:

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

This code attempts to write the 'rating' field to a file after converting the dictionary to JSON. However, this results in a TypeError: string indices must be integers, not str.

The issue stems from the fact that json.dumps() converts the dictionary into a string representation, not a JSON object. To access the data, you must first load the string back into a dictionary using the json.loads() method.

Think of json.dumps() as a save method and json.loads() as a retrieve method. Here's an updated code sample:

<code class="python">import json

r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating']  # Output 3.5
type(r)  # Output str
type(loaded_r)  # Output dict</code>
Copy after login

Now, loaded_r is a dictionary, and you can access its fields as expected.

The above is the detailed content of How to Access Data from Converted JSON Dictionaries in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!