Say i have a file.json that contains the following:
[
{
"name": "Shirt1",
"product_id": "001234"
},
{
"name": "Shirt2",
"product_id": "005678"
}
]
Using Python3, i want to add to both dictionaries the following lines:
"type": "external"
"reviews_allowed": false
This is my code:
import json
import os
with open("file.json", "r", encoding="utf8") as in_file:
INP = json.load(in_file)
DATA = []
for item in INP:
item["type"] = "external"
item["reviews_allowed"] = "false"
DATA.append(item)
with open("file2.json", "w", encoding="utf-8") as out_file:
out_file.write(json.dumps(DATA, indent=2, ensure_ascii=False))
os.rename("file2.json", "file.json")
However, I get the following:
[
{
"name": "Shirt1",
"product_id": "001234",
"type": "external",
"reviews_allowed": "false"
},
{
"name": "Shirt2",
"product_id": "005678",
"type": "external",
"reviews_allowed": "false"
}
]
Is there a way to get rid of the double quotes around false? Thank you very much in advance for your time!
false is recognised as its own type in JSON:
A value can be a string in double quotes, or a number, or
trueorfalseornull, or an object or an array.
In python, the JSON false maps directly to the False bool value:
>>> json.dumps({'val' : False})
'{"val": false}'
The JSON concept false maps directly to the Python concept False. Use this line:
item["reviews_allowed"] = False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With