gpt4 book ai didi

python - 使用 bash 脚本处理 JSON

转载 作者:太空宇宙 更新时间:2023-11-04 09:17:55 24 4
gpt4 key购买 nike

我正在编写一个执行一些操作的 bash 脚本。现在它将一些文件复制到正确的目录中并运行一些命令。我需要这个 bash 脚本来编辑 JSON 文件。本质上,此脚本会将一段 JSON 附加到 file.JSON 中存在的现有 JSON 对象。我不能只追加数据,因为 JSON 片段必须是现有 JSON 对象的一部分(应该添加到 tracks 数组)。那么这可能与 bash 脚本有关吗?我应该只编写另一个 python 或 R 脚本来处理这个 JSON 逻辑,还是有更优雅的解决方案。谢谢你的帮助。

file.JSON looks like this...
{
"formatVersion" : 1,
"tracks" : [
{
"key" : "Reference sequence",
"chunkSize" : 20000,
"urlTemplate" : "seq/{refseq_dirpath}/{refseq}-",
"storeClass" : "JBrowse/Store/Sequence/StaticChunked",
"type" : "SequenceTrack",
"seqType" : "dna",
"category" : "Reference sequence",
"label" : "DNA"
},
{
"type" : "FeatureTrack",
"label" : "gff_track1",
"trackType" : null,
"key" : "gff_track1",
"compress" : 0,
"style" : {
"className" : "feature"
},
"storeClass" : "JBrowse/Store/SeqFeature/NCList",
"urlTemplate" : "tracks/gff_track1/{refseq}/trackData.json"
},
{
"storeClass" : "JBrowse/Store/SeqFeature/NCList",
"style" : {
"className" : "feature"
},
"urlTemplate" : "tracks/ITAG2.4_gene_models.gff3/{refseq}/trackData.json",
"key" : "ITAG2.4_gene_models.gff3",
"compress" : 0,
"trackType" : null,
"label" : "ITAG242.4_gene_models.gff3",
"type" : "FeatureTrack"
},
{
"urlTemplate" : "g-231FRL.bam",
"storeClass" : "JBrowse/Store/SeqFeature/BAM",
"label" : "g-1FRL.bam",
"type" : "JBrowse/View/Track/Alignments2",
"key" : "g-1FRL.bam"
}
]
}

the JSON snippet looks like this ...

{
"urlTemplate": "AX2_filtered.vcf.gz",
"label": "AX2_filtered.vcf.gz",
"storeClass": "JBrowse/Store/SeqFeature/VCFTabix",
"type": "CanvasVariants"
}

最佳答案

帮自己一个忙,安装jq ,那么就很简单了:

jq -n 'input | .tracks += [inputs]' file.json snippet.json > out.json

如果没有合适的解析器,尝试修改结构化数据(如 JSON)是徒劳的,jq 确实让这一切变得简单。

但是,如果您更喜欢通过 Python 来完成它(尽管对于这种任务来说它有点矫枉过正),它与使用 jq 一样直接:

import json

with open("file.json", "r") as f, open("snippet.json", "r") as s, open("out.json", "w") as u:
data = json.load(f) # parse `file.json`
data["tracks"].append(json.load(s)) # parse `snippet.json` and append it to `.tracks[]`
json.dump(data, u, indent=4) # encode the data back to JSON and write it to `out.json`

关于python - 使用 bash 脚本处理 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45040567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com