【问题标题】:Python 3.x/json package cannot convert this json string to listPython 3.x/json 包无法将此 json 字符串转换为列表
【发布时间】:2019-05-28 22:33:25
【问题描述】:

我有这个字符串,我想将其转换为列表:

"{'Attributes': {'a', 'b', 'h'}, 'Group3': {'c'}, 'Group2': {'s', 'm', 'r', 'ac'}}"

我试过json.loads(),它给了我这个错误:

JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

它来自另一个程序,我无法控制引用...单引号或双引号

环境:Python 3.x 导入 json

我的代码:

mystr =  "{'Attributes': {'a', 'b', 'h'}, 'Group3': {'c'}, 'Group2': {'s', 'm', 'r', 'ac'}}"
mylist = json.loads(mystr)

我希望它是一个有效的列表

【问题讨论】:

  • json.loads(mystr.replace("'", "\""))
  • 也许只是一个术语错误,但该 json 中的任何内容都不是 list{'a', 'b', 'h'} 是一个集合
  • 您的字符串不包含有效的 JSON,因此 json 解析器将失败。

标签: python json list


【解决方案1】:

您的字符串不是有效的 JSON。

以下应该可以解决问题:

import json

mystr =  "{'Attributes': ['a', 'b', 'h'], 'Group3': ['c'], 'Group2': ['s', 'm', 'r', 'ac']}" 
mydict = json.loads(mystr.replace("'", "\"")) 
print(mydict)

>>> {'Attributes': ['a', 'b', 'h'], 'Group3': ['c'], 'Group2': ['s', 'm', 'r', 'ac']}

【讨论】:

  • 知道了 - 我认为其他程序正在吐出这个无效的 json。让我处理那部分,如果可能的话,改变它。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
  • 2022-11-15
相关资源
最近更新 更多