python将字典数据保存为json文件

7,317次阅读
没有评论

共计 1152 个字符,预计需要花费 3 分钟才能阅读完成。

目录

一、json 库介绍

二、字典生成 json 文件

1、导入 json 模块 

2、将字典数据保存为 json 文件

(1) 创建一个 python 字典

(2) 指定要保存的 json 文件路径

(3)  将字典数据存为 json 文件

3、读取 json 文件,并打印


一、json 库介绍

方法 作用
json.dumps() 将 python 对象编码成 Json 字符串
json.loads() 将 Json 字符串解码成 python 对象
json.dump() 将 python 中的对象转化成 json 储存到文件中
json.load() 将文件中的 json 的格式转化成 python 对象提取出来

json.dump() 和 json.dumps() 的区别:

  • json.dumps() 是把 python 对象转换成 json 对象的一个过程,生成的是字符串;
import json

x = {'name':'你猜','age':19,'city':'四川'}

#用 dumps 将 python 编码成 json 字符串
print(json.dumps(x))    #{"name": "u4f60u731c", "age": 19, "city": "u56dbu5ddd"}
  • json.dump() 是把 python 对象转换成 json 对象生成一个 fp 的文件流,和文件相关;
import json

x = {'name':'你猜','age':19,'city':'四川'}

#把 python 编码成 json 放在那个文件里
filename = 'pi_x.txt'
with open (filename,'w') as f:
    json.dump(x,f)

python 将字典数据保存为 json 文件

二、字典生成 json 文件


1、导入 json 模块 


import json

2、将字典数据保存为 json 文件


(1) 创建一个 python 字典

dict_data = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

(2) 指定要保存的 json 文件路径

file_path = "test.json"

(3)  将字典数据存为 json 文件

with open(file_path, "w", encoding='utf-8') as json_file:
    json.dump(dict_data, json_file)

 也可以加上参数,如:json.dump(dict_data, json_file, indent=4, ensure_ascii=False)

 json.dump() 函数将字典数据写入指定路径的 JSON 文件中。

3、读取 json 文件,并打印


with open(file_path, "r") as json_file:
    loaded_data = json.load(json_file)
    
print(loaded_data)

打印出读取的数据,确认是否保存成功


原文地址: python 将字典数据保存为 json 文件

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于2024-11-04发表,共计1152字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)