代码之家  ›  专栏  ›  技术社区  ›  ewizard

如何使用str.replace解析这个JSON数据?

  •  0
  • ewizard  · 技术社区  · 7 年前

    更新

    代码:

    print('\n //// jsonData5 at the beginning:\n')
    print(reply)
    print(reply.__class__)
    
    string2 = ''
    string2 = reply.replace("\\", "")
    
    print('\n //// string2:\n')
    print(string2)
    
    string1 = ''
    for index, item in enumerate(res.decode()):
        string1 = string1 + item
        #string = string + item.decode()
    
    string1 = string1.replace("'", "")
    string1 = string1.replace("/", "")
    
    print(string1)
    jsonData6 = json.loads(string1)
    jsonData8 = json.loads(string2)
    res_loaded = jsonData8['res']
    print('\n //// resloaded\n')
    print(res_loaded['node'])
    
    print('\n //// jsonData6[res]\n')
    pprint(jsonData6)
    print('\n //// jsonData5[res]\n')
    pprint(jsonData5)
    print('\n //// jsonData8[res]\n')
    pprint(jsonData8['res']['node'])
    

    输出:

    //// jsonData5 at the beginning:
    
    {"length": 106, "res": "{\"message\": \"New Block Forged\", \"index\": 106, \"transactions\": [{\"sender\": \"0\", \"recipient\": \"4a77509b1ca041d4b41e7983b6292691\", \"amount\": 1}], \"proof\": 299671, \"previous_hash\": \"3a83c09446911419318d671abb3de3523e32bc68dfea7b1a78eb9c459303c0ae\", \"node\": \"4a77509b1ca041d4b41e7983b6292691\"}"}
    <class 'str'>
    
     //// string2:
    
    {"length": 106, "res": "{"message": "New Block Forged", "index": 106, "transactions": [{"sender": "0", "recipient": "4a77509b1ca041d4b41e7983b6292691", "amount": 1}], "proof": 299671, "previous_hash": "3a83c09446911419318d671abb3de3523e32bc68dfea7b1a78eb9c459303c0ae", "node": "4a77509b1ca041d4b41e7983b6292691"}"}
    {"message": "New Block Forged", "index": 112, "transactions": [{"sender": "0", "recipient": "433fc033fdb844aca7d28f93d26550af", "amount": 1}], "proof": 4940, "previous_hash": "86194415a7350a765a8917e2783872ce104f5724fd82ec3647ad8664147e1cc6", "node": "433fc033fdb844aca7d28f93d26550af"}
    Traceback (most recent call last):
      File "alicep2p.py", line 121, in <module>
        jsonData8 = json.loads(string2)
      File "/home/pi/.pyenv/versions/3.6.3/lib/python3.6/json/__init__.py", line 354, in loads
        return _default_decoder.decode(s)
      File "/home/pi/.pyenv/versions/3.6.3/lib/python3.6/json/decoder.py", line 339, in decode
        obj, end = self.raw_decode(s, idx=_w(s, 0).end())
      File "/home/pi/.pyenv/versions/3.6.3/lib/python3.6/json/decoder.py", line 355, in raw_decode
        obj, end = self.scan_once(s, idx)
    json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 27 (char 26)
    

    这是一个不同的错误,然后我看到的一个,它不会加载它。

    我有以下代码:

    print('\n //// jsonData5 at the beginning:\n')
    pprint(reply)
    print(reply.__class__)
    
    string2 = ''
    string2 = reply.replace("'", "")
    string2 = string2.replace('/', "")
    string2 = string2.replace('(', "")
    string2 = string2.replace(')', "")
    
    print('\n //// string2:\n')
    pprint(string2)
    

    控制台输出为:

    //// jsonData5 at the beginning:
    
    ('{"length": 48, "res": "{\\"message\\": \\"New Block Forged\\", \\"index\\": '
     '48, \\"transactions\\": [{\\"sender\\": \\"0\\", \\"recipient\\": '
     '\\"39ca48e4074e41c29374a4a59b1e0481\\", \\"amount\\": 1}], \\"proof\\": '
     '550305, \\"previous_hash\\": '
     '\\"cc64a8b99bc7be84261919159d456a19b204b3694388fe3fe203b0fc3c2d57d7\\", '
     '\\"node\\": \\"39ca48e4074e41c29374a4a59b1e0481\\"}"}')
    <class 'str'>
    
    //// string2:
    
    ('{"length": 48, "res": "{\\"message\\": \\"New Block Forged\\", \\"index\\": '
     '48, \\"transactions\\": [{\\"sender\\": \\"0\\", \\"recipient\\": '
     '\\"39ca48e4074e41c29374a4a59b1e0481\\", \\"amount\\": 1}], \\"proof\\": '
     '550305, \\"previous_hash\\": '
     '\\"cc64a8b99bc7be84261919159d456a19b204b3694388fe3fe203b0fc3c2d57d7\\", '
     '\\"node\\": \\"39ca48e4074e41c29374a4a59b1e0481\\"}"}')
    

    虽然我用 replace() 函数-我是python新手-我做错了什么?或者如何将输出转换为可以访问的内容?

    1 回复  |  直到 6 年前
        1
  •  2
  •   James Lim    7 年前

    您是否正在尝试解析JSON数据?使用 json 包裹

    >>> import json
    >>> dict = json.loads('{"x":"y"}')
    {u'x': u'y'}
    >>>> json.dumps(dict)
    '{"x": "y"}'
    

    在您的示例中,数据是双重编码的,因此需要对其进行两次解析:

    import json
    data = '{"length": 48, "res": "{\\"message\\": \\"New Block Forged\\", \\"index\\": 48, \\"transactions\\": [{\\"sender\\": \\"0\\", \\"recipient\\": \\"39ca48e4074e41c29374a4a59b1e0481\\", \\"amount\\": 1}], \\"proof\\": 550305, \\"previous_hash\\": \\"cc64a8b99bc7be84261919159d456a19b204b3694388fe3fe203b0fc3c2d57d7\\", \\"node\\": \\"39ca48e4074e41c29374a4a59b1e0481\\"}"}'
    json.loads(json.loads(data)['res'])
    

    你只是想 replace 特定字符?

    >>> x = 'abca'
    >>> print(x.replace('a', 'e'))
    ebce
    

    如果您对 pprint 和其他转义字符,将其作为普通字节写入文件:

    with open('out.dat', 'w') as f:
        f.write(my_string)