【问题标题】:Mapping boolean string values to true/false in JSON将布尔字符串值映射到 JSON 中的真/假
【发布时间】:2018-04-03 14:10:38
【问题描述】:

我正在将 CSV 文件转换为 JSON,如下所示:

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)

CSV 文件包含一个可以将值 "true" 和 "false" 作为字符串的列。这些应以true 和false 的形式映射到JSON(不是在True 或False 的Python 样式中)。

有没有可以使用的内置函数?

【问题讨论】:

标签: python json python-3.x csv


【解决方案1】:

我认为最简单的方法是在将 csv 文件的每一行传递给json.dump() 之前对其进行预处理,以将其中包含这些名称的字符串映射到 Python 布尔值——json.dump() 将更改为类型您想要的 JSON 布尔值。这就是我的意思:

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)

CSV 输入示例:

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

示例 JSON 输出:

[
  [
    "1",
    "2",
    true,
    "3",
    "4"
  ],
  [
    "5",
    "6",
    false,
    "7",
    "8"
  ],
  [
    "9",
    "10",
    "non-bool",
    "11",
    "12"
  ]
]

【讨论】:

    猜你喜欢
    • 2019-06-09
    • 2019-07-03
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    相关资源
    最近更新 更多