Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing boolean values in JSON

Tags:

python

json

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!

like image 605
haz14 Avatar asked Aug 24 '26 17:08

haz14


2 Answers

false is recognised as its own type in JSON:

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array.

In python, the JSON false maps directly to the False bool value:

>>> json.dumps({'val' : False})
'{"val": false}'
like image 112
cs95 Avatar answered Aug 26 '26 06:08

cs95


The JSON concept false maps directly to the Python concept False. Use this line:

item["reviews_allowed"] = False
like image 33
Robᵩ Avatar answered Aug 26 '26 08:08

Robᵩ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!