Python JSON Parsing: json.load vs json.loads

Both json.load and json.loads are functions in Python's json module used for parsing JSON data. Here's a breakdown of their differences and how to use them:

json.load()

  • Parses JSON data from a file-like object (e.g., a file opened using open()).
  • Takes a single argument: the file-like object containing JSON data.
  • Returns a Python object representing the parsed JSON data.

Example:

import json

with open('data.json') as f:
    data = json.load(f)

print(data)

json.loads()

  • Parses JSON data from a JSON string.
  • Takes a single argument: the JSON string to parse.
  • Returns a Python object representing the parsed JSON data.

Example:

import json

data = '{"name": "John", "age": 30, "city": "New York"}'

parsed_data = json.loads(data)

print(parsed_data)

In Summary:

  • json.load() is used for loading JSON data from files.
  • json.loads() is used for parsing JSON data from strings.
Python JSON Parsing: json.load vs json.loads Explained

原文地址: https://www.cveoy.top/t/topic/mUoz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录