【问题标题】:how to remove a specific character from a JSON file?如何从 JSON 文件中删除特定字符?
【发布时间】:2020-05-10 11:19:48
【问题描述】:

我有一个 json 文件,其中一个键是一个列表,但它在方括号之前有双引号,另一个在方括号末尾。基本上它使列表成为一个字符串。我想编写一个可以删除那些特定双引号的程序,以便我可以将它用作列表。这是该 json 文件的示例。

{
   "attempts":[{
                 "image_dump":"[ {"x":247,"y":16}, {"x":248,"y":16} ]"
              }]
}

我需要删除键“image_dump”的值的双引号。这样我就可以使用该列表。我尝试使用 replace() 方法,但它替换了每个双引号。 如何使用 python 做到这一点?

【问题讨论】:

  • 您是否尝试将“[ 替换为 [ (右括号也一样)?它应该可以工作,但是如果这不起作用或者您想要更高的精度和灵活性,我建议您检查一下出正则表达式
  • 只需从具有 image_dump 值的字符串中删除第一个和最后一个字符。

标签: python json string list


【解决方案1】:

您可以使用正则表达式将“括号后的引号”的特定组合替换为仅一个括号(请参阅https://docs.python.org/3/library/re.html)。假设您已将文本导入到sample

import re
# Replace text combination of `"[` with `[`
sample = re.sub("\"\[", "[", sample)
# Replace text combination of `]"` with `]`
sample = re.sub("\]\"", "]", sample)
# Try to read json text
json.loads(sample)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多