简体   繁体   English

如何从 JSON 文件中删除特定字符?

[英]how to remove a specific character from a JSON file?

I have a json file where a key is a list but it has Double-quote before the square bracket and the other at the end of the square bracket.我有一个 json 文件,其中一个键是一个列表,但它在方括号之前有双引号,另一个在方括号末尾。 Basically it makes the list a string.基本上它使列表成为一个字符串。 I want to write a program that can remove those specific double quotes so that I can use it as a List.我想编写一个可以删除那些特定双引号的程序,以便我可以将它用作列表。 Here is an example of that json file.这是 json 文件的示例。

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

I need to remove the double quotes for the value of key 'image_dump'.我需要删除键“image_dump”值的双引号。 So that I can use that list.这样我就可以使用该列表。 I tried using the replace() method but it replaces every double quote.我尝试使用 replace() 方法,但它替换了每个双引号。 How do I do it using python?我该如何使用 python?

You can replace the specific combination of "quote following by bracket" with just a bracket by using regular expression (see https://docs.python.org/3/library/re.html ).您可以使用正则表达式将“括号后的引号”的特定组合替换为仅一个括号(请参阅https://docs.python.org/3/library/re.ZFC35FDC70D5FC69D269883A822C7A5 )。 Assuming you have imported the text to sample假设您已将文本导入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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM