如何使用Python编辑JSON文件?

时间:2015-03-21 03:13:34

标签: python xml json raspberry-pi

我已经查看了几个问题并进行了相应的更改,但我的python脚本仍无效。对于Python来说还是一个新手,所以如果我犯了一个简单的错误,我会道歉......

我目前正在向我的网页发送XML响应,以显示我的JSON文件中的值。我测试了脚本的XML部分,它工作正常 - 但是当我添加代码来编辑我的JSON文件时,XML响应不会加载。这就是我所得到的 - 我做错了什么?

#!/usr/bin/env python

import cgi
import cgitb
import json


with open('../../../var/www/data.json', 'r+') as f:
    json_data = json.load(f)
    json_data[0]['A'] = '7'
    f.seek(0)
    f.write(json.dumps(json_data))
    f.truncate()

with open('../../../var/www/data.json') as data_file:    
    data = json.load(data_file)

cgitb.enable()


print "Content-Type: text/xml"     
print # blank line, end of headers
print "<?xml version='1.0' encoding='UTF-8' ?><inputs><data>"+data[0]["A"]+"</data></inputs>"

我也试过这个......但它也没有用:

#!/usr/bin/env python

import cgi
import cgitb
import json

with open('../../../var/www/data.json', 'r') as f:
    json_data = json.load(f)
    json_data[0]["A"] = "7"

with open('../../../var/www/data.json', 'w') as f
    f.write(json.dumps(json_data))

with open('../../../var/www/data.json') as data_file:    
     data = json.load(data_file)

cgitb.enable()



print "Content-Type: text/xml"     
print # blank line, end of headers
print "<?xml version='1.0' encoding='UTF-8' ?><inputs><data>"+data[0]["A"]+"</data></inputs>"

这是我的JSON文件:

[
    {
        "A": "11",
        "B": "4",
        "C": "",
        "D": "basement",
        "E": "Digital",
        "F": "",
        "G": "",
        "H": "",
        "I": "",
        "J": "",
        "K": "",
        "L": "",
        "M": "",
        "N": "on",
        "O": "off",
        "P": "1"
    },
    {
        "A": "11",
        "B": "3",
        "C": "",
        "D": "Silver",
        "E": "Digital",
        "F": "",
        "G": "",
        "H": "",
        "I": "",
        "J": "",
        "K": "",
        "L": "",
        "M": "",
        "N": "ON",
        "O": "OFF",
        "P": "1"
    },
    {
        "A": "12",
        "B": "3",
        "C": "",
        "D": "Bench",
        "E": "Digital",
        "F": "",
        "G": "",
        "H": "",
        "I": "",
        "J": "",
        "K": "",
        "L": "",
        "M": "",
        "N": "ON",
        "O": "OFF",
        "P": "1"
    }
]

2 个答案:

答案 0 :(得分:0)

下次应该包含错误/控制台输出。

在你的第二个档案中:

  • 第11行缺少行尾的:

答案 1 :(得分:0)

我得到了它的工作。下面是我的新python代码:

#!/usr/bin/env python

import cgi
import cgitb
import json



#this worked to open the json file, rewrite it, and then open it again for reading
with open("../../../var/www/data.json", "r+") as jsonFile:
    data = json.load(jsonFile)
    data[0]["A"] = "2"
    jsonFile.seek(0)  # rewind
    jsonFile.write(json.dumps(data))
    jsonFile.truncate()

newJsonFile = open("../../../var/www/data.json", "r")
newData = json.load(newJsonFile)

cgitb.enable()


print "Content-Type: text/xml"     
print # blank line, end of headers
print "<?xml version='1.0' encoding='UTF-8' ?><inputs><data>"+newData[0]["A"]+"</data></inputs>"