【问题标题】:can't convert text data to json无法将文本数据转换为 json
【发布时间】:2020-05-10 22:58:06
【问题描述】:

我正在尝试将以下 (json) 字符串转换为 python 数据类型:

data = "{'id': 26, 'photo': '/media/f082b5af-ad0.png', 'first_name': 'Islam', 'last_name': 'Mansour', 'email': 'islammansour06+8@gmail.com', 'city': 'Giza', 'cv': '/media/fbb61609-442.pdf', 'reference': 'Facebook', 'campaign': OrderedDict([('id', 2), ('name', 'javascript')]), 'status': 'Invitation Sent', 'user': None, 'at': '2020-01-20', 'time': '23:02:58.359179', 'technologies': [OrderedDict([('id', 46), ('name', 'Django'), ('category', OrderedDict([('id', 24), ('name', 'Framework'), ('_type', 'skill')]))])]}"

我正在尝试使用

将其转换为 JSON

json.loads(data.replace("\'", "\""))

但我遇到以下错误

json.decoder.JSONDecoderError: Expecting value: line 1 column 219 (char 218)

【问题讨论】:

  • 这种格式的数据是从哪里来的?

标签: json django python-3.x


【解决方案1】:

问题是您的数据不是有效的 json。

主要问题从这里开始:[OrderedDict([('id', 46), ('name', 'Django'), ('category', OrderedDict([('id', 24), ('name', 'Framework'), ('_type', 'skill')]))])]}。这看起来像是一些 python 对象的字符串表示。

下面是您的 json 数据的更友好的表示。

我已经标记了有问题的部分(用**)(基本上到处都有 OrderedDict)。

{
"id":26,
"photo":"/media/f082b5af-ad0.png",
"first_name":"Islam",
"last_name":"Mansour",
"email":"islammansour06+8@gmail.com",
"city":"Giza",
"cv":"/media/fbb61609-442.pdf",
"reference":"Facebook",
"campaign":**OrderedDict**([("id",
2), ("name", "javascript")]), "status":"Invitation Sent",
"user":None,
"at":"2020-01-20",
"time":"23:02:58.359179",
"technologies":[
**OrderedDict**([("id",
46),
("name",
"Django")
]("category", OrderedDict([("id", 24), ("name", "Framework"), ("_type", "skill")]))])]
}```

You could try making use of an [online json parser][1] which might give you some friendlier output. 


  [1]: http://json.parser.online.fr/

【讨论】:

    【解决方案2】:

    如前所述,OrderedDict 不是正确的 JSON。但这是正确的python。

    修复它:

    from collections import OrderedDict  # direct import because this is as this in your string
    import json
    jsonCorrect = json.dumps(eval(data))
    json.loads(jsonCorrect)  # it works
    

    【讨论】:

    • 为什么要在这里导入 OrderedDict ?
    • 只是因为 eval 将运行数据,因为它是一些 python 代码并返回它。该代码调用 OrderedDict。因此,在提供的解决方案中的评论。你可以看看 eval 的文档字符串。
    • 我很高兴@IslamMansour
    • @IslamMansour 请注意运行eval 的安全问题,除非您真正了解这样做的后果,否则不应使用它。
    • 确实@MattSeymour,但知道用例......好吧......显然别无选择。 :-(
    【解决方案3】:

    不确定为什么要添加 replace 调用。应该只使用以下内容:

    json.loads(data)
    

    你可以阅读它here

    【讨论】:

    • 另外,正如@Matt Seymour 提到的,您没有有效的 JSON。
    猜你喜欢
    • 2022-07-13
    • 2020-02-16
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多