【问题标题】:python How to convert a dictionary string to the corresponding dictionary?python 如何将字典字符串转换为对应的字典?
【发布时间】:2020-12-29 23:40:25
【问题描述】:

我无法使用 ast.literal_eval() 将字典字符串转换回字典。我想原因可能是字典字符串中有很多空值。一个例子是

'{"paper_id": "94550656", "_pdf_hash": "42b3e1bd9c4740192f22d8725d470218e86301c8", "abstract": [], "body_text": [], "bib_entries": {"BIBREF0": {"title": "Solving ratio-dependent predator-prey system with constant effort harvesting using homotopy perturbation method", "authors": [{"first": "R", "middle": ["G"], "last": "Abdoul", "suffix": ""}, {"first": "A", "middle": [], "last": "Barari", "suffix": ""}, {"first": "D", "middle": ["D"], "last": "Ganji", "suffix": ""}], "year": 2008, "venue": "J. Math. Prob. Eng", "link": "16827035"}, "BIBREF1": {"title": "Numerical analysis of strongly nonlinear oscillation systems using He\'s max-min method", "authors": [{"first": "H", "middle": [], "last": "Babazadeh",.....

如何将其转换为普通字典以进行进一步处理? ###############################################

代码如下:

json_list = []
with open(s2orc_path, 'r') as s2orcReader:
for line in s2orcReader.readlines():
    json_list.append(line)
s2orc_samples = json.dumps(json_list)
s2orc_data = json.loads(s2orc_samples)

在此之后,当我尝试执行 ast.literal_eval(s2orc_data[0]) 时,它给了我错误 ValueError: malformed node or string

【问题讨论】:

  • 你能不能把null换成None再做一次?
  • 它实际上是 JSON 吗? (如果是这样@Roharui 也会有问题,例如true/True。)给minimal reproducible example
  • 是的,更换后可以使用。谢谢!

标签: python json string


【解决方案1】:
import json

data = """{"paper_id": "94550656", "_pdf_hash": "42b3e1bd9c4740192f22d8725d470218e86301c8", "abstract": [], "body_text": [], "bib_entries": {"BIBREF0": {"title": "Solving ratio-dependent predator-prey system with constant effort harvesting using homotopy perturbation method", "authors": [{"first": "R", "middle": ["G"], "last": "Abdoul", "suffix": ""}, {"first": "A", "middle": [], "last": "Barari", "suffix": ""}, {"first": "D", "middle": ["D"], "last": "Ganji", "suffix": ""}], "year": 2008, "venue": "J. Math. Prob. Eng", "link": "16827035"}}}"""""
dictionary_data = json.loads(data)

【讨论】:

    【解决方案2】:

    您可以为此使用 json.loads:

    import json
    
    str = "'[{"age":"luke", "id":0}, {"age":"bob", "id":1}]'"
    dict = json.loads(str)
    print(str) # [{u'age': u'luke', u'id': 0}, {u'age': u'bob', u'id': 1}]
    

    【讨论】:

    • 那么你的数据可能是无效的,也许你使用 None 而不是 null
    • 只要确保 json 有效
    • 我没有制作数据,你想问艾伦研究所这个
    【解决方案3】:

    试试dictionary = dict(your_dictionary_string)
    如果这不起作用,请使用json 模块和json.loads(your_dictionary_string)

    【讨论】:

    • dict(dict_repr_or_json)高兴,会是ValueError“字典更新序列元素 #0 的长度为 1;需要 2” .
    • true,在将其传递给“dict”之前,您应该将 null 替换为 None,依此类推。或者只使用 json.loads()。
    • 这不是我要说的,dict("{'foo': None}") 会因为同样的原因不高兴。
    【解决方案4】:

    你可以尝试用逗号分割输入字符串:

    ps = input_string.spit(",")
    

    在冒号mlike上拆分ps的每个元素:

    for seg in ps:
      k = seg.split(":")
      out_dict[k[0]] = k[1]
    

    【讨论】:

    • 我强烈建议不要尝试重新实现 JSON 解析。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2013-02-03
    • 2018-05-19
    • 2013-03-13
    • 2017-03-23
    • 1970-01-01
    相关资源
    最近更新 更多