python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python创建json文件

如何使用Python创建json文件

作者:devid008

众所周知JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,这篇文章主要给大家介绍了关于如何使用Python创建json文件的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下

前言

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于阅读和编写,也易于机器解析和生成。在 Python 中,我们可以使用内置的 json 模块来创建和处理 JSON 数据。本文将介绍如何使用 Python 创建 json 文件。

1.使用 json.dump() 方法

使用 json.dump() 方法可以将 Python 对象序列化为 JSON 格式,并写入到文件中。该方法接收两个参数:待序列化的对象和文件对象。以下是一个示例:

import json
 
data = {'name': 'John', 'age': 30, 'city': 'New York'}
 
with open('data.json', 'w') as f:
    json.dump(data, f)

在这个示例中,我们使用了 json.dump() 方法将 Python 字典对象 data 序列化为 JSON 格式,并将其写入到文件 data.json 中。

2.使用 json.dumps() 方法

除了使用 json.dump() 方法直接将 Python 对象写入到文件中,我们还可以使用 json.dumps() 方法将 Python 对象序列化为 JSON 字符串,然后将其写入文件。以下是一个示例:

import json
 
data = {'name': 'John', 'age': 30, 'city': 'New York'}
 
with open('data.json', 'w') as f:
    json_str = json.dumps(data)
    f.write(json_str)

在这个示例中,我们首先使用 json.dumps() 方法将 Python 字典对象 data 序列化为 JSON 字符串,然后使用文件对象的 write() 方法将其写入文件 data.json 中。

3.使用 json.JSONEncoder() 方法

我们还可以使用 json.JSONEncoder() 方法来创建自定义的编码器,将 Python 对象序列化为 JSON 字符串,然后将其写入文件。以下是一个示例:

import json
 
class Person:
    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city
 
def person_encoder(obj):
    if isinstance(obj, Person):
        return {'name': obj.name, 'age': obj.age, 'city': obj.city}
    return json.JSONEncoder.default(obj)
 
person = Person('John', 30, 'New York')
 
with open('data.json', 'w') as f:
    json_str = json.dumps(person, default=person_encoder)
    f.write(json_str)

在这个示例中,我们首先定义了一个自定义的类 Person,然后定义了一个自定义的编码器 person_encoder,将 Person 对象序列化为 JSON 格式。最后,我们使用 json.dumps() 方法将 Person 对象序列化为 JSON 字符串,并将其写入文件 data.json 中。

补充:python创建文件并写入json

import json
import os
import uuid

PATH = 'D:/SecurityData'
if not os.path.exists(PATH):
    os.makedirs(PATH)

fw = open('{}/Security.json'.format(PATH), 'a+')
fr = open('{}/Security.json'.format(PATH), 'r')
fw.write(json.dumps({
    'name': 'user_name',
    'uuid': str(uuid.uuid1())
}, ensure_ascii=False) + '\n')
fw.flush()

总结

本文介绍了三种方法来创建 JSON 文件:使用 json.dump() 方法、使用 json.dumps() 方法、使用 json.JSONEncoder() 方法。在实际开发中,我们可以根据具体需求选择不同的方法。

您可能感兴趣的文章:
阅读全文