1

I'm converting a CSV file into JSON like this:

import os
import csv
import json

with open(args.infile, encoding="utf-8") as csv_file:
  csv_rows = list(csv.DictReader(csv_file))

with open(args.outfile, "w", encoding="utf-8") as json_file:
  json.dump(csv_rows, json_file, ensure_ascii=False, indent=2)

The CSV file contains a column which can have the values "true" and "false" as strings. These shall be mapped to the JSON as true and false (not in the Python style of True or False).

Is there a built-in function which I can use?

Robert Strauch
  • 12,055
  • 24
  • 120
  • 192
  • 1
    bool(distutils.util.strtobool(some_string)) Answered here: https://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python – dbandjelly Apr 03 '18 at 14:14
  • 2
    Possible duplicate of [Converting from a string to boolean in Python?](https://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python) – pault Apr 03 '18 at 14:20
  • As far as I can see this converts the string to Python's `True` or `False`. These values however are not valid in JSON where it must be `true` or `false`? – Robert Strauch Apr 03 '18 at 14:23
  • 1
    Note that: When you output the value `True` with json-library's dump function it is automatically converted to `true` (javascript-syntax). This is the purpose of the library! – Anton vBR Apr 03 '18 at 14:29
  • I **don't** think this is a duplicate of [Converting from a string to boolean in Python?](https://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python) – martineau Apr 03 '18 at 15:24

1 Answers1

1

I think the easiest way to do it would be to preprocess each row of the csv file before passing it to json.dump() to map strings with those names in them to Python booleans—which the json.dump() will change into the type of JSON boolean values you desire. This is what I mean:

import os
import csv
import json

with open(args.infile, newline='', encoding="utf-8") as csv_file:
    csv_rows = [[True if row[field] == 'true' else
                 False if row[field] == 'false' else
                 row[field] for field in row] for row in csv.DictReader(csv_file)]

with open(args.outfile, "w", encoding="utf-8") as json_file:
    json.dump(csv_rows, json_file, ensure_ascii=False, indent=2)

Sample CSV input:

Field Name1,Field Name2,Field Name3,Field Name4,Field Name5
1,2,true,3,4
5,6,false,7,8
9,10,non-bool,11,12

Sample JSON output:

[
  [
    "1",
    "2",
    true,
    "3",
    "4"
  ],
  [
    "5",
    "6",
    false,
    "7",
    "8"
  ],
  [
    "9",
    "10",
    "non-bool",
    "11",
    "12"
  ]
]
martineau
  • 119,623
  • 25
  • 170
  • 301