转换" True"真正的JSON Python

时间:2016-04-05 15:23:14

标签: python json

我正在阅读有一个布尔值的json。使用json.load()在Python中加载文件时,我得到True(我已阅读规范)。

{"XYZ": true}

据我所知,我需要使用json.dumps()来处理这个问题。我的转储看起来像这样。

convert = json.dumps({"true": True, "false": False})

我的负担是这样的:

jdata = json.load(open(json_path))

打印jdata时,我得到:

{u'XYZ': True}

我的问题是,如何在加载json文件后将True转换为true?稍后在我的代码中,我使用jdata.iteritems()来获取所有键和值。

如果我这样写

jdata = json.load(open(json_path))
convert = json.dumps(jdata, {"true": True, "false": False})

它会打印出来:

{"XYZ": true}

但是我无法做到

for key, value in convert.iteritems():
    #code

因为我收到了这个错误:

AttributeError: 'str' object has no attribute 'iteritems'

我该如何解决这个问题?

修改 这是代码

def ReadAndValidate(directory, json_path):

    jdata = json.load(open(json_path))
    path = findAllFiles(directory)

    if os.path.isdir(path):
        for root, dirs, files in os.walk(path):
            for key, value in jdata.iteritems():
                for name in files:
                    with open(os.path.join(root, name)) as fle:
                        content = fle.read()
                    if name.endswith('.txt') and re.search(Wordboundry(key), content):
                        print "Name", key, "was found in", name, "\n"
                        writeToFile(value, content, name, key)
                   else:
                       print "Name", key, "was not found in", name"


def writeToFile(value, file_content, file, name):
    if type(value) is list:
        nrOfvalue = ' '.join([str(myValue) for myValue in value])
        nrOfvalue = "[ " + nrOfvalue + " ]"
        content = regFindName(name, nrOfvalue, file_content)
    else:
        content = regFindName(name, value, file_content)
    writeToFile(file, content)

我正在使用argumentparser,其中目录可以是" C \ Mydir \ Dir1"和json_path" C:\ MyDir \ Dir1 \ myjson.json

myjson包含:

{"XYZ": true}

函数试图找到" XYZ"在一个文件中。 Leys说它发现在文件" myFile.txt"其中包含:

XYZ = false;

如果名称匹配,我想用true替换false。 " myFile.txt"中的预期输出应该是:

XYZ = true

regFindName()找到" name" (ex XYZ)使用regex ++

1 个答案:

答案 0 :(得分:5)

我相信你误解了json.loadsjson.dumps(及其堂兄弟,json.loadjson.dump)的角色。

json.dumps(或json.dump)将Python对象转换为根据JSON标准格式化的字符串(或文件)。

json.loads(或json.load)将JSON格式的字符串(或文件)转换为相应的Python对象。

考虑这个程序:

import json

orig_python_object = { "XYZ": True }
json_string = json.dumps(orig_python_object)
new_python_object = json.loads(json_string)

assert orig_python_object == new_python_object
assert isinstance(orig_python_object, dict)
assert isinstance(new_python_object, dict)
assert isinstance(json_string, str)

for key, value in new_python_object.iteritems():
    pass

当然,.iteritems()的结果不能.dumps().dumps()的结果是str,而不是dict

但是,您可以将str(通过文件,套接字或载体鸽)传输到另一个程序,而其他程序可以.loads()将其转换回Python对象。

回到你的问题:

  
    

如何在加载json文件后将“True”转换为true?

  

您可以将其转换回JSON。

python_object = json.load(open("somefile.json"))
for k,v in python_object.iteritems():
    # some code
    pass
json_str = json.dumps(python_object)

assert 'true' in json_str
assert 'True' in str(python_object)

编辑:

您在问题中发布了大部分程序,这使得问题所在的地方更加明显。如果我是你,我会做两件事之一:

1)我会像这样修改writeToFile

def writeToFile(value, file_content, file, name):
    if type(value) is list:
        nrOfvalue = ' '.join([str(myValue) for myValue in value])
        nrOfvalue = "[ " + nrOfvalue + " ]"
        content = regFindName(name, nrOfvalue, file_content)
    elif isinstance(value, bool):
        content = regFindName(name, str(value).lower(), file_content)
    else:
        content = regFindName(name, value, file_content)
    writeToFile(file, content)

或者,2)我会像这样修改myjson.json

{"XYZ": "true"}