代码之家  ›  专栏  ›  技术社区  ›  Yingqiang Gao

python如何将字典字符串转换为相应的字典?

  •  0
  • Yingqiang Gao  · 技术社区  · 4 年前

    '{"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

    0 回复  |  直到 4 年前
        1
  •  0
  •   Zaraki Kenpachi    4 年前
    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
  •  0
  •   Luke_    4 年前

    你可以用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}]
    
        3
  •  -2
  •   finn b    4 年前

    dictionary = dict(your_dictionary_string)
    如果不起作用,使用 json json.loads(your_dictionary_string)

        4
  •  -3
  •   itprorh66    4 年前

    您可以尝试将输入字符串拆分为逗号,如下所示:

    ps = input_string.spit(",")
    

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

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