python 字典key单引号变双引号

背景:
  str1 = "{'a':1,'b':2,'c':3}"
把字典格式的字符串str1转成字典

import json
s_dic = json.loads(str1)
报错信息:json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

 

解决思路:

方法一:(不建议使用此方法)

str1 = "{'a':1,'b':2,'c':3}"
s_dic = eval(str1)

方法二:

#json格式校验(key 单引号变双引号,尽量不要用eval做转换)
def correctSingleQuoteJSON(s):
    rstr = ""
    escaped = False
    for c in s:
        if c == "'" and not escaped:
            c = '"'  # replace single with double quote
        elif c == "'" and escaped:
            rstr = rstr[:-1]  # remove escape character before single quotes
        elif c == '"':
            c = '\\' + c  # escape existing double quotes
        escaped = (c == "\\")  # check for an escape character
        rstr += c  # append the correct json

    return rstr

str2 = correctSingleQuoteJSON(str1)

s_dic = json.loads(str2)

posted @ 2023-07-02 11:35  匿名好友  阅读(221)  评论(0编辑  收藏  举报