美文网首页Python学习
Python | 将json数据转换成字典

Python | 将json数据转换成字典

作者: Quora文选 | 来源:发表于2019-02-16 06:22 被阅读1次

    要求:把下面的数据转换成字典:

    2019年02月15日 21:08:20

    i:I love seajay
    from:AUTO
    to:AUTO
    smartresult:dict
    client:fanyideskweb
    salt:15483356026163
    sign:0e6fc7b099ab52173b750e4f1fe2e967
    ts:1548335602616
    bv:563490a3a59c96d89a5868bde7ab81c1
    doctype:json
    version:2.1
    keyfrom:fanyi.web
    action:FY_BY_CLICKBUTTION
    typoResult:false
    

    解决:

    1. 将以上文件存在txt文件中,并命名为:原始数据.txt
    2. 利用python来实现json数据的转换:
    data = {}
    filename = "原始数据.txt"
    with open(filename) as f:
        lines = f.readlines()
    
    for line in lines:
        key = line.split(":")[0]
        value = line.split(":")[1].strip()
        data[key] = value
        print("data['%s'] = '%s'" % (key, value))
    print(data)
    

    也可以这样写:

    data = {}
    filename = "原始数据.txt"
    with open(filename) as f:
        lines = f.readlines()
    
    for line in lines:
        key = line[: line.index(':')]
        value = line[line.index(':') + 1:].rstrip()
        data[key] = value
        print("data['%s'] = '%s'" % (key, value))
    print(data)
    

    输出结果为:

    >>> %Run 'json转字典.py'
    data['i'] = 'I love seajay'
    data['from'] = 'AUTO'
    data['to'] = 'AUTO'
    data['smartresult'] = 'dict'
    data['client'] = 'fanyideskweb'
    data['salt'] = '15483356026163'
    data['sign'] = '0e6fc7b099ab52173b750e4f1fe2e967'
    data['ts'] = '1548335602616'
    data['bv'] = '563490a3a59c96d89a5868bde7ab81c1'
    data['doctype'] = 'json'
    data['version'] = '2.1'
    data['keyfrom'] = 'fanyi.web'
    data['action'] = 'FY_BY_CLICKBUTTION'
    data['typoResult'] = 'false'
    {'i': 'I love seajay', 'from': 'AUTO', 'to': 'AUTO', 'smartresult': 'dict', 'client': 'fanyideskweb', 'salt': '15483356026163', 'sign': '0e6fc7b099ab52173b750e4f1fe2e967', 'ts': '1548335602616', 'bv': '563490a3a59c96d89a5868bde7ab81c1', 'doctype': 'json', 'version': '2.1', 'keyfrom': 'fanyi.web', 'action': 'FY_BY_CLICKBUTTION', 'typoResult': 'false'}
    

    相关文章

      网友评论

        本文标题:Python | 将json数据转换成字典

        本文链接:https://www.haomeiwen.com/subject/iwxveqtx.html