Home > Backend Development > Python Tutorial > How to Access Data from JSON Converted from Dictionary?

How to Access Data from JSON Converted from Dictionary?

Barbara Streisand
Release: 2024-10-20 21:05:30
Original
295 people have browsed it

How to Access Data from JSON Converted from Dictionary?

Accessing Data in JSON Converted from Dictionary

When attempting to access data from a JSON object converted from a dictionary, you may encounter issues as demonstrated in the following code:

r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
file.write(str(r['rating']))
Copy after login

This code aims to write the rating value in the JSON object r to a file. However, an error occurs because json.dumps() returns a string representation of the dictionary, not a JSON object.

Solution: Loading JSON String into Dictionary

To access data from the JSON string, you need to load it back into a dictionary using json.loads(). This method retrieves the JSON object from the string.

import json

r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)  # Save as string
loaded_r = json.loads(r)  # Retrieve as dictionary
print(loaded_r['rating'])  # Output: 3.5
Copy after login

Understanding json.dumps() and json.loads()

  • json.dumps(): Converts a dictionary into a JSON string for storage or transmission.
  • json.loads(): Decodes a JSON string into a dictionary for use in your program.

By understanding the difference between saving and retrieving JSON, you can access data from a dictionary that has been converted to and from a JSON string.

The above is the detailed content of How to Access Data from JSON Converted from Dictionary?. 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