2017-07-11 89 views
0

我正在寫一個bash腳本來做一些事情。現在它將幾個文件複製到正確的目錄並運行一些命令。我需要這個bash腳本來編輯一個JSON文件。從本質上講,這個腳本會將JSON片段附加到存在於file.JSON中的現有JSON對象。我不能只追加數據,因爲JSON片段必須是現有JSON對象的一部分(應添加到tracks數組中)。那麼這可能與一個bash腳本有關嗎?我應該只編寫另一個python或R腳本來處理這個JSON邏輯,還是有更好的解決方案。謝謝你的幫助。與bash腳本一起使用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" 
     } 

回答

2

請你幫個忙,並安裝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` 
+0

優秀的解決方案,正是我尋找。乾杯! – Developing