在bash中使用awk合并两个Json文件

时间:2015-10-15 04:04:03

标签: json linux bash ubuntu awk

我尝试在一个文件中合并两个json文件,但是有一个条件,例如:如果文件1有例如:testa:result>失败,文件b包含相同的行,但结果不同,例如: testa:结果>传递,我想文件1它将用文件2的结果更新,我有这行与awk命令,但它只合并没有这个条件的文件:

awk 'BEGIN{print "{"} FNR > 1 && last_file == FILENAME {print line} FNR == 1 {line = ""} FNR==1 && FNR != NR {printf ","} FNR > 1 {line = $0} {last_file = FILENAME} END{print "}"}' json_files/* > json_files/all_merged.json

我需要帮助。

1 个答案:

答案 0 :(得分:1)

我建议使用python来完成任务。考虑这个例子:

import json
from pprint import pprint

fileName1 = "file1.json" # file1 contains something like { "Testname": "color", "result": "fail" }
fileName2 = "file2.json" # file2 contains something like { "AnotherTestname": "color2", "result": "pass" }
fileNameTo = "file3.json"

def visualize(data, prompt):
    print(prompt)
    pprint(data)
    raw_input("Press <Enter> to continue: ") # this line pauses the execution

def loadData(fname):
    with open(fname, "r") as f:
        return json.load(f)

jd1 = loadData(fileName1)
visualize(jd1, "Data from %s" % fileName1)
jd2 = loadData(fileName2)
visualize(jd2, "Data from %s" % fileName2)
jd3 = jd1.copy() # create a copy of data from file1, this step can be avoided if you don't need unmodified jd1
visualize(jd3, "Data after copying")
jd3.update(jd2) # merge copy of data from file1 with file2, updating corresponding keys
visualize(jd3, "Data after merging")
with open("file3.json", "w") as f3:
    json.dump(jd3, f3)

这个版本的脚本获得了一些&#34; interactiveity&#34;,它可以让你控制每个执行步骤的数据状态。我刚检查过它按预期执行数据合并。请尝试针对您的测试数据运行它并查看输出。