如何在没有重复的json数组中存储多个项目?

时间:2018-02-13 20:56:40

标签: python arrays json twisted

我正在尝试在python中开发某种对等系统。当客户端连接到我的服务器时,客户端会发送特定位置内的所有文件。当客户端将数据发送到服务器时,它通过json执行此操作。当服务器从客户端获取信息时,它将打印出来。一个例子:

{
    "Localfiles": [{
        "IPAddress": ["217.120.103.158"],
        "FileLength": 363031,
        "FileName": "chromeicon.png"
    }, {
        "IPAddress": ["217.120.103.158"],
        "FileLength": 363031,
        "FileName": "chromeicon.png"
    }]
}

当客户端两次发送有关位置的信息(仅包含1个文件的文件夹)时,它会打印。我怎样才能这样做,以便当我将数据附加到我的json数组时,它不会显示为重复。

这是我的代码:

from twisted.internet import reactor, protocol
import os, json

data = {}  
data['Localfiles'] = []
def test(datas):
    test = json.loads(datas)
    for x in range(0,(len(test['Localfiles']))):
        if x not in data:
            data['Localfiles'].append({
                'FileName':test['Localfiles'][x]['FileName'],
                'FileLength':test['Localfiles'][x]['FileLength'],
                'IPAddress':test['Localfiles'][x]['IPAddress']
            })

    print json.dumps(data) +"\n"
    return data

class Echo(protocol.Protocol):
    def dataReceived(self, data):
        try:
            self.transport.write(json.dumps(test(data)))                  
        except ValueError:
            print "nope"

def main():
    factory = protocol.ServerFactory()
    factory.protocol = Echo
    reactor.listenTCP(5000,factory)
    reactor.run()

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

迭代了值后,如何折叠字典:

import json
dic = '{"Localfiles":[{"IPAddress": ["217.120.103.158"],"FileLength": 363031,"FileName": "chromeicon.png"},{"IPAddress": ["217.120.103.158"],"FileLength": 363031,"FileName":"chromeicon.png"}]}'

data = {}  
data["Localfiles"] = []
def test(datas):
    test = json.loads(str(datas))
    for x in range(0,(len(test["Localfiles"]))):
        if x not in data:
            data["Localfiles"].append({
                "FileName":test["Localfiles"][x]["FileName"],
                "FileLength":test["Localfiles"][x]["FileLength"],
                "IPAddress":test["Localfiles"][x]["IPAddress"]
            })

    L = data["Localfiles"]
    data["Localfiles"] = list({v['FileName']:v for v in L}.values())

    return data

这给了我:

{'Localfiles': [{'FileLength': 363031,
   'FileName': 'chromeicon.png',
   'IPAddress': ['217.120.103.158']}]}