JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,通常用于将数据从一个系统传输到另一个系统,或者将数据保存到文件中。JSON是一种文本格式,易于人类阅读和编写,同时也易于计算机解析和生成。本文主要介绍Python中,JSON格式字符串与 Python 对象之间的转换的方法。

1、json.dumps() 和 json.loads() 方法

使用 json.dumps() 方法将 Python 对象转换为 JSON 格式字符串。

使用 json.loads() 方法将 JSON 格式字符串解析为 Python 对象。

import json

# Python 对象转换为 JSON 字符串
data = {
  "person": {
    "name": "John Doe",
    "age": 35,
    "address": {
      "street": "123 Main St",
      "city": "Anytown",
      "zipcode": "12345"
    },
    "email": [
      "john.doe@example.com",
      "johndoe@gmail.com"
    ]
  },
  "is_active": True,
  "orders": [
    {
      "order_id": "A123",
      "products": [
        {
          "product_id": "P001",
          "name": "Product 1",
          "price": 19.99
        },
        {
          "product_id": "P002",
          "name": "Product 2",
          "price": 29.99
        }
      ]
    },
    {
      "order_id": "B456",
      "products": [
        {
          "product_id": "P003",
          "name": "Product 3",
          "price": 39.99
        }
      ]
    }
  ]
}
json_string = json.dumps(data)
print("JSON字符串:\n"+json_string)
# JSON 字符串解析为 Python 对象
parsed_data = json.loads(json_string)
print("JSON对象:")
print(parsed_data)

2、json.dump() 和 json.load() 方法(文件读写)

使用 json.dump() 方法将 Python 对象写入 JSON 文件。

使用 json.load() 方法从 JSON 文件中读取并解析 Python 对象。

import json

# Python 对象转换为 JSON 字符串
data = {
  "person": {
    "name": "John Doe",
    "age": 35,
    "address": {
      "street": "123 Main St",
      "city": "Anytown",
      "zipcode": "12345"
    },
    "email": [
      "john.doe@example.com",
      "johndoe@gmail.com"
    ]
  },
  "is_active": True,
  "orders": [
    {
      "order_id": "A123",
      "products": [
        {
          "product_id": "P001",
          "name": "Product 1",
          "price": 19.99
        },
        {
          "product_id": "P002",
          "name": "Product 2",
          "price": 29.99
        }
      ]
    },
    {
      "order_id": "B456",
      "products": [
        {
          "product_id": "P003",
          "name": "Product 3",
          "price": 39.99
        }
      ]
    }
  ]
}
with open('data.json', 'w') as json_file:
    json.dump(data, json_file)

# 从 JSON 文件中读取并解析 Python 对象
with open('data.json', 'r') as json_file:
    parsed_data = json.load(json_file)

print("JSON对象:")
print(parsed_data)

3、json.JSONEncoder 和 json.JSONDecoder 类

自定义 JSON 编码器和解码器,然后使用这些自定义类。

import json

# Python 对象转换为 JSON 字符串
data = {
  "person": {
    "name": "John Doe",
    "age": 35,
    "address": {
      "street": "123 Main St",
      "city": "Anytown",
      "zipcode": "12345"
    },
    "email": [
      "john.doe@example.com",
      "johndoe@gmail.com"
    ]
  },
  "is_active": True,
  "orders": [
    {
      "order_id": "A123",
      "products": [
        {
          "product_id": "P001",
          "name": "Product 1",
          "price": 19.99
        },
        {
          "product_id": "P002",
          "name": "Product 2",
          "price": 29.99
        }
      ]
    },
    {
      "order_id": "B456",
      'numbers': {1, 2, 3},
      "products": [
        {
          "product_id": "P003",
          "name": "Product 3",
          "price": 39.99
        }
      ]
    }
  ]
}
# 自定义 JSON 编码器
class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        return super().default(obj)
json_string = json.dumps(data, cls=MyEncoder)
print("JSON字符串:\n"+json_string)

# 自定义 JSON 解码器
def as_set(dct):
    if 'numbers' in dct:
        return set(dct['numbers'])
    return dct
# JSON 字符串解析为 Python 对象
parsed_data = json.loads(json_string, object_hook=as_set)
print("JSON对象:")
print(parsed_data)

4、json.JSONEncoder 的 default 方法和 object_hook 参数

使用 default 方法自定义编码器,然后使用 object_hook 参数自定义解码器。

import json

# Python 对象转换为 JSON 字符串
data = {
  "person": {
    "name": "John Doe",
    "age": 35,
    "address": {
      "street": "123 Main St",
      "city": "Anytown",
      "zipcode": "12345"
    },
    "email": [
      "john.doe@example.com",
      "johndoe@gmail.com"
    ]
  },
  "is_active": True,
  "orders": [
    {
      "order_id": "A123",
      "products": [
        {
          "product_id": "P001",
          "name": "Product 1",
          "price": 19.99
        },
        {
          "product_id": "P002",
          "name": "Product 2",
          "price": 29.99
        }
      ]
    },
    {
      "order_id": "B456",
      'numbers': {1, 2, 3},
      "products": [
        {
          "product_id": "P003",
          "name": "Product 3",
          "price": 39.99
        }
      ]
    }
  ]
}
# 自定义 JSON 编码器的 default 方法
def custom_encoder(obj):
    if isinstance(obj, set):
        return list(obj)
    raise TypeError(f'Object of type {type(obj)} is not JSON serializable')
json_string = json.dumps(data, default=custom_encoder)
print("JSON字符串:\n"+json_string)

# 自定义 JSON 解码器
def custom_decoder(dct):
    if 'numbers' in dct:
        return set(dct['numbers'])
    return dct
# JSON 字符串解析为 Python 对象
parsed_data = json.loads(json_string, object_hook=custom_decoder)
print("JSON对象:")
print(parsed_data)

5、simplejson 模块

使用 simplejson 模块,它是一个第三方 JSON 库,功能与内置的 json 模块类似。

import simplejson as json


# Python 对象转换为 JSON 字符串
data = {
  "person": {
    "name": "John Doe",
    "age": 35,
    "address": {
      "street": "123 Main St",
      "city": "Anytown",
      "zipcode": "12345"
    },
    "email": [
      "john.doe@example.com",
      "johndoe@gmail.com"
    ]
  },
  "is_active": True,
  "orders": [
    {
      "order_id": "A123",
      "products": [
        {
          "product_id": "P001",
          "name": "Product 1",
          "price": 19.99
        },
        {
          "product_id": "P002",
          "name": "Product 2",
          "price": 29.99
        }
      ]
    },
    {
      "order_id": "B456",
      "products": [
        {
          "product_id": "P003",
          "name": "Product 3",
          "price": 39.99
        }
      ]
    }
  ]
}
json_string = json.dumps(data)
print("JSON字符串:\n"+json_string)
# JSON 字符串解析为 Python 对象
parsed_data = json.loads(json_string)
print("JSON对象:")
print(parsed_data)

推荐文档

相关文档

大家感兴趣的内容

随机列表