5个Python读取和写入JSON文件以及编码和解码的用法

JSON是JavaScript对象表示法的缩写,它是一种数据结构化的格式,非常类似于计算机编程中的映射概念。映射由键和相应的值组成。在映射中,键必须是唯一的。

file

JSON是一种轻量级的数据表示格式,以文本形式在文件中表示,其语法借鉴了创建JavaScript对象所用的语法。大量数据被转换为JSON格式,以便在各种编程语言中进行简单处理,并传输到其他节点。它是处理API调用时请求和响应的最常用格式。

JSON格式接受的数据类型

JSON的键必须是字符串。大多数语言会隐式地将任何其他数据类型转换为字符串。JSON的值可以是字符串,布尔值,整数,浮点数,另一个JSON对象或JSON数组。

以下是一个有效的JSON文件(data.json)的示例:

{
  "name": "Jason",
  "age": 21,
  "address": {
    "street": "1 Main Street",
    "city": "Los Angeles",
    "zipcode": 90001
  },
  "married": false
}

这里,“address”键的值是另一个JSON。键“married”具有布尔类型的值。

请注意,JSON不支持注释。这里给出的所有代码片段也与python 3兼容。

Python中最接近JSON的数据类型是字典。Python支持使用名为json的模块,这是一个内置的python库,来进行字典,JSON和字符串之间的转换。

读取JSON文件

JSON文件通常的扩展名是.json。然而,只要它包含一个有效的JSON,python就支持解析任何文件扩展名。要读取一个json文件并将数据填充到字典中,我们使用json.load()函数。这个函数以文件对象作为参数。以下是一个使用json.load()的示例:

示例代码片段:

import json

with open("data.json") as f:
    p = json.load(f)
    print(p, type(p))
    print(p["name"], "is", "married" if p["married"] else "not married")

上述示例的输出:

{'name': 'Jason', 'age': 21, 'address': {'street': '1 Main Street', 'city': 'Los Angeles', 'zipcode': 90001}, 'married': False} <class 'dict'>
Jason is not married

这里f是文件对象。json.load()返回一个字典。

上述代码片段使用了python的if else格式。

将字符串或字节数组读取为字典

Json模块允许用户将形式为字符串,字节或字节数组的json解析为字典。这是使用函数json.loads()完成的。注意这个函数名与前面描述的函数名的相似性。load()期望一个文件对象作为参数,而loads()期望一个字符串作为参数。前者读取文件并隐式调用后者,即loads()。

示例代码片段:

import json

with open("data.json") as f:
    file_data = f.read()
p = json.loads(file_data)
print(p, type(p))
print(p["name"], "is", "married" if p["married"] else "not married")

上述示例的输出:

{'name': 'Jason', 'age': 21, 'address': {'street': '1 Main Street', 'city': 'Los Angeles', 'zipcode': 90001}, 'married': False} <class 'dict'>
Jason is not married

将字典写入JSON文件

只有字符串,字节数组或字节可以写入文件。因此,必须将字典转换为JSON格式的字符串,才能写入json文件。这是使用函数json.dump()完成的。这个函数接受字典和文件对象作为参数。它不返回任何东西。以下是一个示例。

示例代码片段:

import json

json_dict = {
    "name": "Jason",
    "age": 21,
    "address": {
        "street": "1 Main Street",
        "city": "Los Angeles",
        "zipcode": 90001
    },
    "married": False
}

print("Type of json_dict:", type(json_dict))

with open("data.json", "w") as f:
    json.dump(json_dict, f, indent=4)

上述示例的输出:

Type of json_dict: <class 'dict'>

data.json
{
    "name": "Jason",
    "age": 21,
    "address": {
        "street": "1 Main Street",
        "city": "Los Angeles",
        "zipcode": 90001
    },
    "married": false
}

请注意,json文件的格式化使用4个空格作为制表符。这是由于在json.dump()函数中使用了“indent”参数。

将JSON格式的字符串写入文件

在前一个例子中,将字典解析为字符串并写入文件是使用一个函数,一条语句完成的。在这里,那一步被分为两步:首先将字典转换为字符串,保存到一个变量中,然后写入文件。

示例python代码片段:

import json

json_dict = {
    "name": "Jason",
    "age": 21,
    "address": {
        "street": "1 Main Street",
        "city": "Los Angeles",
        "zipcode": 90001
    },
    "married": False
}

print("Type of json_dict:", type(json_dict))

with open("data.json", "w") as f:
    v = json.dumps(json_dict)
    print("v has value", v, "and is of type", type(v))
    f.write(v)

上述示例的输出:

Type of json_dict: <class 'dict'>
v has value {"name": "Jason", "age": 21, "address": {"street": "1 Main Street", "city": "Los Angeles", "zipcode": 90001}, "married": false} and is of type <class 'str'>

data.json
{"name": "Jason", "age": 21, "address": {"street": "1 Main Street", "city": "Los Angeles", "zipcode": 90001}, "married": false}

请注意,data.json文件没有格式化。这是因为在json.dumps()函数中省略了“indent”参数。

Golang时间time.Parse解析中的两个坑
Golang泛型实现PHP中array_intersect函数
标签:

发表我的评论

电子邮件地址不会被公开。 必填项已用*标注

97 + 94 =

ajax-loader