我正在尝试使用Python将CSV数据(MAC地址和信号强度值)写入JSON文件,但是数据仅写入第一个字段。如何获得每个信号强度值以写入正确的MAC地址?
wifi rss
b0:7f:b9:bc:f0:e2 -56
34:a8:4e:fc:13:50 -59
34:a8:4e:fd:3c:50 -57
34:a8:4e:fd:3c:53 -55
34:a8:4e:fc:13:53 -58
b0:7f:b9:bc:f1:02 -81
b0:7f:b9:bc:f0:e0 -55
ec:58:ea:59:a3:53 -89
b0:7f:b9:bc:f0:40 -69
b0:7f:b9:bc:f0:42 -67
00:1d:7e:42:e0:ba -60
b0:7f:b9:bc:f0:f0 -63
b0:7f:b9:bc:f0:50 -72
b0:7f:b9:bc:f0:f2 -64
0a:8d:cb:65:6d:70 -85
06:8d:cb:65:6d:70 -85
import csv
import json
import pandas as pd
my_csv = pd.read_csv('my_data.csv')
fo = open('my_json.json','w')
wifi = my_csv.wifi
f = pd.read_csv('my_data.csv',usecols=[2])
rss = f.rss
fieldnames = (wifi)
reader = csv.DictReader( f, wifi)
for row in reader:
json.dump(row, fo, indent = 2)
fo.write('\n')
"b0:7f:b9:bc:f0:e2": "rss",
"34:a8:4e:fc:13:50": null,
"34:a8:4e:fd:3c:50": null,
"34:a8:4e:fd:3c:53": null,
"34:a8:4e:fc:13:53": null,
"b0:7f:b9:bc:f1:02": null,
"b0:7f:b9:bc:f0:e0": null,
"ec:58:ea:59:a3:53": null,
"b0:7f:b9:bc:f0:40": null,
"b0:7f:b9:bc:f0:42": null,
"00:1d:7e:42:e0:ba": null,
"b0:7f:b9:bc:f0:f0": null,
"b0:7f:b9:bc:f0:50": null,
"b0:7f:b9:bc:f0:f2": null,
"0a:8d:cb:65:6d:70": null,
答案 0 :(得分:0)
您正在将插入数据转储到起始行的json中。因此它正在打印相同。您需要附加数据。您可以将数据追加到任何字典,然后将完整的字典转储到Json
# Out of Loop
data = {}
#Inside Loop
data.append("What ever Json You want to insert")
#Outside Loop
json.dump(data, fo,[other arguments])
答案 1 :(得分:0)
with open(file_name, 'w') as jsonfile:
json.dump(dictionary, jsonfile, indent=4)
请注意,在您通过wifi和rss创建dictionary
后,应使用此功能。
答案 2 :(得分:0)
这是一种方法。
演示:
import json
import pandas as pd
my_csv = pd.read_csv('my_data.csv', sep="\s*")
result = {"wifi": {k:v for k, v in my_csv.to_dict('split')["data"]}}
with open('my_json.json', 'w') as outfile:
json.dump(result, outfile)
答案 3 :(得分:0)
因为您使用的是熊猫,所以可以使用
to_json
方法在这里描述
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html
对于这种情况,我认为以下代码可以解决问题。
import pandas as pd
dataFrame = pd.read_csv('my_data.csv')
dataFrame.set_index('wifi').to_json('path_of.json')