通过Python读写JSON [英] Reading and Writing JSON through Python

查看:124
本文介绍了通过Python读写JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

read.json文件:

read.json file :

{
    "Username" : "admin",
    "Password" : "admin",
    "Iterations" : 5,
    "Decimal" : 5.5,
    "tags" : ["hello", "bye"],
    "Value" : 5
}

program.py文件:

program.py File:

import json 
with open('read.json') as data_file:
    data = json.load(data_file)

data = str(data)
data.replace("'",'""',10)
f = open("write.json", "w")
f.write(data)

write.json文件:

write.json file :

{'Username': 'admin', 'Password': 'admin', 'Iterations': 5, 'Decimal': 5.5, 'tags': ["hello", "bye"], 'Value': 5}

我想要实现的目标:

  1. 从read.json文件中读取JSON数据
  2. 从程序中的JSON解析和修改一些值
  3. 写入另一个write.json文件(JSON格式)

我的代码中没有错误,但是write.json不包含双引号(")中的值,而是将值包装在单引号中,使其不是正确的JSON格式.

There are no errors in my code, but the write.json does not contain the values in double quotes(""), it rather as the values wrapped in single quotes making it not a proper JSON format.

需要进行哪些更改才能使write.json文件包含正确的JSON格式,并且还对"write.json"文件进行漂亮写入".

推荐答案

您可以直接将json数据转储到文件中. 文档

you can directly dump json data to file. Docs

import json
with open('read.json', 'w') as outfile:
    json.dump(data, outfile, sort_keys=True, indent=4)
    # sort_keys, indent are optional and used for pretty-write 

要从文件中读取json:

To read json from file:

with open('read.json') as data_file:    
    data = json.load(data_file)

这篇关于通过Python读写JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆