Convert "True" to true JSON Python
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping
--
Chapters
00:00 Convert &Quot;True&Quot; To True Json Python
01:58 Accepted Answer Score 9
03:30 Thank you
--
Full question
https://stackoverflow.com/questions/3643...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #json
#avk47
ACCEPTED ANSWER
Score 9
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"}