简体   繁体   中英

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. 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.

{
   "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'. So that I can use that list. I tried using the replace() method but it replaces every double quote. How do I do it using 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 ). Assuming you have imported the text to 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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