如何将数组转换为 JSON?

How can I convert an array to JSON?

我有一个数组需要转换为 JSON 文件。有一个保存数据的文本文件。但是不明白为什么只加了一条记录

import collections
list = []
with open("file.txt") as f:
    for line in f:
        info = line.split()
        lists = ("ip" + " " + info[0].replace(":", " ").split()[0] + " " + "port" + " " + info[0].replace(":", " ").split()[1] + " " + "region" + " " + info[1].replace("-", " ").split()[0]).split()
        list.append(lists)
        d = collections.defaultdict(dict)
        for l in list:
            d[l[0]] = l[1]
            d[l[2]] = l[3]
            d[l[4]] = l[5]
print(json.dumps(d))
with open("proxy.json", "w") as f:
    f.write(json.dumps(d))

文本文件示例:

154.0.5.178:8080 ZA-N-S! - 
119.28.156.115:3128 KR-N - 
207.144.111.230:8080 US-H - 
3.20.236.208:49205 US-H-S - 
217.60.194.43:8080 IR-N! - 
190.61.41.106:999 CO-N-S + 

我得到的: enter image description here

info[1].replace("-", " ").split()[0] 

将始终return一个值!试试这个:

import json

alist = []
with open("file.txt") as f:
    for line in f:
        info = line.split()
        data = {"ip": info[0].split(":")[0], "port": info[0].split(":")[1],"region": info[1].split("-")}
        alist.append(data)
print(json.dumps(alist))
with open("proxy.json", "w") as f:
    f.write(json.dumps(alist))