Python - 无效的 JSON 格式 - 如何解析 [英] Python - Invalid JSON format - how to parse

查看:82
本文介绍了Python - 无效的 JSON 格式 - 如何解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取以下 JSON 格式的数据:

I am getting data in the following JSON format:

{
  address:[
    "test1"
  ],
  city:"test2",
  country:"test3",
  postal_code:"test4",
  state:"test5"
}

虽然我试图通过以下方式解析它:

While I am trying to parse it via:

json.loads(data)

我收到一个错误:期望用双引号括起来的属性名称

有没有办法在python中解析它?

Is there a way to parse it in python ?

提前致谢,

推荐答案

不言而喻,更好的解决方案是在源头修复损坏的数据.但是如果你不能这样做,你可以尝试用一个简单的正则表达式来解决这个问题.很简单,就像如果你抛出任何更复杂的东西就会失败",但作为一个快速而肮脏的解决方案可能就足够了:

It goes without saying that the better solution would be to fix the broken data at the source. But if you can't do that, you could try and fix the problem with a simple regex. Simple, as in "will fail if you throw anything more complicated at it", but likely sufficient as a quick and dirty solution:

import re
import json
with open("almost.json") as infile:
    jstring = infile.read()
data = json.loads(re.sub(r"(\w+):", r'"\1":', jstring))

这篇关于Python - 无效的 JSON 格式 - 如何解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆