gpt4 book ai didi

python - 字符串转 Json Python

转载 作者:太空宇宙 更新时间:2023-11-04 09:26:54 25 4
gpt4 key购买 nike

Print(Json_text)
'{\n \n acorn: "",\n acorn_type: "",\n area_name: "Glasgow",\n beds_max: 2,\n beds_min: 2,\n }

我试图通过以下方式解决它:

json_text = re.sub(r'\n', '',json_text)
json_text = re.sub(r' ', '',json_text)

然后结果:

print(json_text)
'{acorn:"",acorn_type:"",area_name:"Glasgow",beds_max:2,beds_min:2,branch_id:"32896"}

然后我尝试转换成Json格式:

json_text= json.dumps(json_text)
json_text = json.loads(json_text)

但最终的值是一个字符串。

json_text['area_name']
TypeError: string indices must be integers

我认为是因为键值没有引号 ("")

最佳答案

您需要进行替换以使其可解析为 json:

In [120]: text = '{\n                    \n                        acorn: "",\n                        acorn_type: "",\n                        area_name: "Glasgow",\n                        beds_max: 2,\
...: n beds_min: 2,\n }'

In [121]: json.loads(re.sub(r'\b([^:",]+)(?=:)', r'"\1"', re.sub(r'\s*|,\s*(?=\}$)', '', text)))
Out[121]:
{'acorn': '',
'acorn_type': '',
'area_name': 'Glasgow',
'beds_max': 2,
'beds_min': 2}

首先,我们需要删除所有的空格和结尾的,:

In [122]: re.sub(r'\s*|,\s*(?=\}$)', '', text)                                                                                                                                                              
Out[122]: '{acorn:"",acorn_type:"",area_name:"Glasgow",beds_max:2,beds_min:2}'

现在,在返回的字符串上,我们需要为键添加双引号:

In [123]: re.sub(r'\b([^:",]+)(?=:)', r'"\1"', re.sub(r'\s*|,\s*(?=\}$)', '', text))                                                                                                                        
Out[123]: '{"acorn":"","acorn_type":"","area_name":"Glasgow","beds_max":2,"beds_min":2}'

现在,json.loads 会做:

In [124]: json.loads(re.sub(r'\b([^:",]+)(?=:)', r'"\1"', re.sub(r'\s*|,\s*(?=\}$)', '', text)))                                                                                                            
Out[124]:
{'acorn': '',
'acorn_type': '',
'area_name': 'Glasgow',
'beds_max': 2,
'beds_min': 2}

使用名称:

In [125]: text                                                                                                                                                                                              
Out[125]: '{\n \n acorn: "",\n acorn_type: "",\n area_name: "Glasgow",\n beds_max: 2,\n beds_min: 2,\n }'

In [126]: text_wo_whitespaces = re.sub(r'\s*|,\s*(?=\}$)', '', text)

In [127]: text_quoted = re.sub(r'\b([^:",]+)(?=:)', r'"\1"', text_wo_whitespaces)

In [128]: json.loads(text_quoted)
Out[128]:
{'acorn': '',
'acorn_type': '',
'area_name': 'Glasgow',
'beds_max': 2,
'beds_min': 2}

关于python - 字符串转 Json Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57232758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com