Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert "True" to true JSON Python [closed]

Tags:

python

json

Im reading json which has a boolean. When loading the file in Python with json.load(), I get True (I've read the specs).

{"XYZ": true}

As I understood I need to use json.dumps() to handle this. My dumps look like this.

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

And my load like this:

jdata = json.load(open(json_path))

When printing jdata I get:

{u'XYZ': True}

My question is, how do I convert the True to true after loading the json file? Later in my code I use the jdata.iteritems() to get all the keys and values.

If I write like this

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

it will print out:

{"XYZ": true}

But then I can't do

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

because I get this error:

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

How can I fix this?

EDIT Here is the code

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)

I am using argumentparser where directory could be "C\Mydir\Dir1" and json_path "C:\MyDir\Dir1\myjson.json

myjson contains:

{"XYZ": true}

Function tries to find "XYZ" in a file. Leys say it finds it in the file "myFile.txt" which contains:

XYZ = false;

I wanna replace false with true if the name matches. The expected output in "myFile.txt" should be:

XYZ = true

The regFindName() finds the "name" (ex XYZ) by using regex++

like image 794
gants Avatar asked Feb 07 '23 08:02

gants


1 Answers

I believe you misunderstand the roles of json.loads and json.dumps (and their cousins, json.load and json.dump).

json.dumps (or json.dump) converts a Python object to a string (or file) which is formatted according to the JSON standard.

json.loads (or json.load) converts a string (or file) in JSON format to the corresponding Python object.

Consider this program:

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

Of course one cannot .iteritems() the result of .dumps(). The result of .dumps() is a str, not a dict.

However, you can transmit that str (via file, socket, or carrier pigeon) to another program, and that other program can .loads() it to turn it back into a Python object.

Returning to your question:

how do I convert the "True" to true after loading the json file?

You do so by converting it back to 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)

EDIT :

You've posted a larger part of your program in your question, which makes it more apparent where the problem lies. If I were you, I'd do one of two things:

1) I'd modify writeToFile like so:

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)

Or, 2) I'd modify myjson.json like so:

{"XYZ": "true"}
like image 191
Robᵩ Avatar answered Feb 10 '23 05:02

Robᵩ