【问题标题】:Is there a way to remove certain strings from a JSON File using Python?有没有办法使用 Python 从 JSON 文件中删除某些字符串?
【发布时间】:2020-03-25 12:43:38
【问题描述】:

我想用另一个字符串替换 JSON 文件中的一个字符串。给出的所有解决方案都使用 json.load() 对 JSON 文件执行任何必要的操作。但是在尝试了很多之后,我找不到替换字符串的方法。我尝试以 Python 读取文件的常用方式读取它,使用 open()replace() 但这不适用于 JSON 文件。

这是 JSON 文件的一部分。

    "61" : {
      "a" : 0.0,
      "b" : 1.0,
      "c" : "[ 0, 1 ]"
    },

我希望它是:

    "61" : {
      "a" : 0.0,
      "b" : 1.0,
      "c" : [ 0, 1 ]
    },

这是我尝试使用 open()replace() 的方法。

        fin = open(JSON_IN)
        fout = open(JSON_OUT, "w+")

        line_f = fin.readline()

        x1 = '"['
        while line_f:

            print(line_f)
            if x1 in line_f:
                line_f.replace('\"[', '[')
                line_f.replace(']\"', ']')
                fout.write(line_f)

            else:
                fout.write(line_f)
            line_f = fin.readline

我希望将 "[ 更改为 [。有什么办法可以做到这一点使用 Python?

【问题讨论】:

  • 如果没有引号,则不是字符串。
  • 好的,同意。有没有办法删除它们?我只是希望引号消失。 @ScottHunter
  • 更好地展示你的代码
  • text = text.replace('"[', '[').replace(']"', ']') ?但它会改变文件中的所有"[ ]"。如果你想在某些地方做,那么你可能必须单独处理每一行。
  • 使用上下文管理器来处理文件。

标签: python json python-3.x string


【解决方案1】:

replace() 不会更改变量中的值,但它会返回您必须分配给变量的新值

line_f = line_f.replace(...)

如果将" 放入' ',则不需要\,因为它会搜索带有\ 的文本

代码

fin = open(JSON_IN)
fout = open(JSON_OUT, "w+")

x1 = '"['

for line_f in fin:

    print(line_f)

    if x1 in line_f:
        line_f = line_f.replace('"[', '[').replace(']"', ']')

    fout.write(line_f)

如果您想在所有文件中更改它,那么您甚至可以尝试

fin = open(JSON_IN)
fout = open(JSON_OUT, "w+")

text = fin.read()
text = text.replace('"[', '[').replace(']"', ']')
fout.write(text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 2018-03-07
    • 2017-06-16
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    相关资源
    最近更新 更多