广告位联系
返回顶部
分享到

python json jsonl的用法介绍

python 来源:互联网 作者:佚名 发布时间:2024-08-31 23:30:54 人浏览
摘要

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛用于在客户端和服务器之间传输数据。以下是 Python 中使用 JSON 的一些常见用法: 1.将 Python 对象转换为 JSON 字符串 使用json.dum

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛用于在客户端和服务器之间传输数据。以下是 Python 中使用 JSON 的一些常见用法:

1. 将 Python 对象转换为 JSON 字符串

使用 json.dumps() 函数将 Python 对象(如字典、列表等)转换为 JSON 字符串。

1

2

3

4

5

6

7

8

9

10

11

12

13

import json

 

# Python 字典

data = {

    "name": "Alice",

    "age": 30,

    "city": "New York",

    "skills": ["Python", "Machine Learning"]

}

 

# 转换为 JSON 字符串

json_str = json.dumps(data)

print(json_str)

输出示例:

{"name": "Alice", "age": 30, "city": "New York", "skills": ["Python", "Machine Learning"]}

2. 将 JSON 字符串解析为 Python 对象

使用 json.loads() 函数将 JSON 字符串解析为 Python 对象(如字典、列表等)。

1

2

3

4

5

json_str = '{"name": "Alice", "age": 30, "city": "New York", "skills": ["Python", "Machine Learning"]}'

 

# 将 JSON 字符串解析为 Python 字典

data = json.loads(json_str)

print(data)

输出示例:

{'name': 'Alice', 'age': 30, 'city': 'New York', 'skills': ['Python', 'Machine Learning']}

3. 将 Python 对象写入 JSON 文件

使用 json.dump() 函数将 Python 对象写入到 JSON 文件中。

1

2

3

4

5

6

7

8

9

10

11

12

import json

 

data = {

    "name": "Alice",

    "age": 30,

    "city": "New York",

    "skills": ["Python", "Machine Learning"]

}

 

# 将 Python 对象写入 JSON 文件

with open('data.json', 'w') as json_file:

    json.dump(data, json_file)

4. 从 JSON 文件读取数据

使用 json.load() 函数从 JSON 文件中读取数据并解析为 Python 对象。

1

2

3

4

5

6

import json

 

# 从 JSON 文件读取数据

with open('data.json', 'r') as json_file:

    data = json.load(json_file)

    print(data)

输出示例:

{'name': 'Alice', 'age': 30, 'city': 'New York', 'skills': ['Python', 'Machine Learning']}

5. 自定义 JSON 编码

如果你有自定义的类对象并想要将其转换为 JSON,可以通过实现自定义的编码器:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import json

 

class Employee:

    def __init__(self, name, age, position):

        self.name = name

        self.age = age

        self.position = position

 

# 自定义的 JSON 编码器

def encode_employee(obj):

    if isinstance(obj, Employee):

        return {'name': obj.name, 'age': obj.age, 'position': obj.position}

    raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")

 

# 创建 Employee 对象

employee = Employee("John", 28, "Software Engineer")

 

# 使用自定义编码器将对象转换为 JSON 字符串

json_str = json.dumps(employee, default=encode_employee)

print(json_str)

输出示例:

{"name": "John", "age": 28, "position": "Software Engineer"}

6. 格式化 JSON 输出

使用 json.dumps() 时,可以通过 indent 参数生成格式化的 JSON 字符串,便于阅读。

1

2

3

4

5

6

7

8

9

10

11

12

import json

 

data = {

    "name": "Alice",

    "age": 30,

    "city": "New York",

    "skills": ["Python", "Machine Learning"]

}

 

# 生成格式化的 JSON 字符串

json_str = json.dumps(data, indent=4)

print(json_str)

输出示例:

1

2

3

4

5

6

7

8

9

{

    "name": "Alice",

    "age": 30,

    "city": "New York",

    "skills": [

        "Python",

        "Machine Learning"

    ]

}

7. 处理复杂对象

如果需要序列化更复杂的对象,可以通过自定义 JSONEncoder 类来处理。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import json

 

class Employee:

    def __init__(self, name, age, position):

        self.name = name

        self.age = age

        self.position = position

 

class EmployeeEncoder(json.JSONEncoder):

    def default(self, obj):

        if isinstance(obj, Employee):

            return {'name': obj.name, 'age': obj.age, 'position': obj.position}

        return super().default(obj)

 

employee = Employee("John", 28, "Software Engineer")

 

# 使用自定义的编码器将对象转换为 JSON 字符串

json_str = json.dumps(employee, cls=EmployeeEncoder)

print(json_str)

输出示例:

{"name": "John", "age": 28, "position": "Software Engineer"}

JSONL

JSONL(JSON Lines)是一种简单的文件格式,专门用于存储多个JSON对象,每个对象占用一行。JSONL文件的扩展名通常为 .jsonl 或 .ndjson(Newline Delimited JSON)。这种格式在处理大量结构化数据时非常有效,因为它允许逐行读取和处理数据。

下面是JSONL的常见用法示例,包括如何在Python中读取和写入JSONL格式的数据。

1. JSONL 文件的结构

一个JSONL文件可能看起来如下:

1

2

3

{"name": "Alice", "age": 30, "city": "New York"}

{"name": "Bob", "age": 25, "city": "Los Angeles"}

{"name": "Charlie", "age": 35, "city": "Chicago"}

每一行都是一个有效的JSON对象,行与行之间用换行符 \n 分隔。

2. 读取 JSONL 文件

使用Python读取JSONL文件时,可以逐行处理文件中的JSON对象:

1

2

3

4

5

6

7

8

import json

 

# 读取 JSONL 文件

with open('data.jsonl', 'r') as jsonl_file:

    for line in jsonl_file:

        # 解析每一行的 JSON 对象

        data = json.loads(line)

        print(data)

输出示例:

1

2

3

{'name': 'Alice', 'age': 30, 'city': 'New York'}

{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}

{'name': 'Charlie', 'age': 35, 'city': 'Chicago'}

3. 写入 JSONL 文件

写入JSONL文件时,可以逐行将多个JSON对象写入文件,每个对象占用一行:

1

2

3

4

5

6

7

8

9

10

11

12

13

import json

 

# 准备要写入的多个 JSON 对象

data_list = [

    {"name": "Alice", "age": 30, "city": "New York"},

    {"name": "Bob", "age": 25, "city": "Los Angeles"},

    {"name": "Charlie", "age": 35, "city": "Chicago"}

]

 

# 写入 JSONL 文件

with open('data.jsonl', 'w') as jsonl_file:

    for data in data_list:

        jsonl_file.write(json.dumps(data) + '\n')

4. 追加写入 JSONL 文件

如果需要追加数据到已有的JSONL文件中,可以使用追加模式 'a':

1

2

3

4

5

6

7

8

import json

 

# 要追加写入的 JSON 对象

new_data = {"name": "Diana", "age": 28, "city": "Houston"}

 

# 追加写入 JSONL 文件

with open('data.jsonl', 'a') as jsonl_file:

    jsonl_file.write(json.dumps(new_data) + '\n')

5. 处理大数据集

由于JSONL格式允许逐行读取和处理数据,特别适合用于处理大数据集。比如当数据量较大时,可以用下面的方式逐行读取并处理,而不需要将整个文件一次性加载到内存中:

1

2

3

4

5

6

7

8

import json

 

# 逐行处理大数据集

with open('large_data.jsonl', 'r') as jsonl_file:

    for line in jsonl_file:

        data = json.loads(line)

        # 对每一行的数据进行处理

        process_data(data)

6. 与Pandas集成

如果你需要将JSONL文件的数据加载到Pandas DataFrame中,Pandas的 read_json 方法也支持读取JSONL格式的数据:

1

2

3

4

5

import pandas as pd

 

# 使用 Pandas 读取 JSONL 文件

df = pd.read_json('data.jsonl', lines=True)

print(df)

输出示例:

      name  age         city
0    Alice   30    New York
1      Bob   25  Los Angeles
2  Charlie   35     Chicago

总结

JSONL格式是一种非常实用的数据存储格式,特别适合处理大型、结构化的数据集。使用它的主要优点包括:

  • 逐行读取:有效处理大文件,节省内存。
  • 简便性:每一行都是独立的JSON对象,便于解析和处理。
  • 灵活性:可以很容易地将数据追加到已有文件中。

通过上述方法,您可以轻松地在Python中读取、写入和处理JSONL格式的数据。


版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 :
相关文章
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计