通过分组将数据从CSV转换为JSON

时间:2018-08-25 11:08:18

标签: json csv jq

csv数据示例(第一行是列标题,后跟三行数据);

floor,room,note1,note2,note3
floor1,room1,2people
floor2,room4,6people,projector
floor6,room5,20people,projector,phone

我需要json中的输出,但是按楼层分组,就像这样;

floor
    room
    note1
    note2
    note3

    room
    note1
    note2
    note3

floor
    room
    note1
    note2
    note3

    room
    note1
    note2
    note3

因此,所有floor1房间都在各自的json分组中,然后是floor2房间等。

在查看哪些工具以及任何特定功能方面,请有人指出正确的方向。 jq +类别。我已经进行了一些搜索,并且陷入了很多与csvtojson,jq和一些python脚本相关的不同帖子之间。理想情况下,我想将解决方案包含在shell脚本中,而不是单独的程序/语言中(我有sys admin的经验,但没有程序员)。

非常感谢

1 个答案:

答案 0 :(得分:0)

也许这可以帮助您入门。

使用Python之类的编程语言通过逗号分隔将CSV数据转换为字典数据结构,并使用JSON库将字典转储为JSON。

我假设您实际上希望每层楼有一个以上的房间,因此我可以自由地对输入数据进行一些调整。

decoder_target_data

如果您随后运行该脚本并将其通过管道传输到for idx in range(X_train.shape[0]): X_train_s = np.expand_dims(X_train[idx], axis=0) y_train_s = np.expand_dims(y_train[idx], axis=0) y_train_s1 = np.expand_dims(y_train[idx+1], axis=0) encoder_input_data = X_train_s decoder_input_data = y_train_s decoder_target_data = y_train_s1 model.fit([encoder_input_data, decoder_input_data], decoder_target_data, epochs=50, validation_split=0.2) (JQ只是用于在屏幕上漂亮地打印输出;实际上并不需要),您将看到:

import json

csv = """floor1,room1,note1,note2,note3
floor1,room2,2people
floor1,room3,3people
floor2,room4,6people,projector
floor2,room5,3people,projector
floor3,room6,1person
"""

response = {}

for line in csv.splitlines():
    fields = line.split(",")
    floor, room, data = fields[0], fields[1], fields[2:]
    if floor not in response:
        response[floor] = {}
    response[floor][room] = data

print json.dumps(response)