2016-09-26 6 views
1

簡単に言えば、私は2つのデータセットを結合しようとしています。私はgrep/bashまたはpythonを使用するために開いています。jsonファイルをvlookupと似たCSVと組み合わせる

  1. 読むディレクトリ/ MEDIAID

  2. .jsonファイル名が.CSVで行と一致した場合におけるJSONファイルの内容をコピーし、

  3. .jsonファイルファイル名を読みますその行(いない場合は、単にスキップ)

INPUTデータ

File1.csv

testentry, 1234 
testentry1, 6789 

INPUTデータ(ファイル名がチェックするMEDIAIDある)

1234.json

[ 
{"id":"1", "text":"Nice man!"}, 
{"id":"2", "text":"Good job"} 
] 

6789.json

[ 
{"id":"1", "text":"Test1"}, 
{"id":"2", "text":"Test2"} 
] 
GREPを使っ

所望の出力データの.csv

testentry, 1234, Nice man!, Good job 
testentry1, 6789, Test1, Test2 

私の試み進行しているが、私はチェックするJSONファイル名を取得し、それらのデータを渡すことはできません。

#!/usr/bin/env bash 

indir="$HOME/indir" 
outdir="$HOME/outdir" 

cd "$indir" || exit 
mkdir -p "$outdir" || exit 
for f in *.csv; do 
    [[ -f $f ]] || continue 
    lines=() 
    while IFS=, read -ra cols; do 
     if ((${#cols[@]} != 2)); then 
      echo "Sorry buddy, you'll have to use a real CSV parser to handle: $f" >&2 
      exit 1 
     fi 
     # Does the basename match the contents of the first column? 
     if [[ ${cols[0]} == "${f%.*}" ]]; then 
      echo "Match found in $f" 
     fi 
     lines+=("${cols[0]},${cols[1]}") 
    done <"$f" 
    # something with JQ to read the json filename, and pass its data into the row 
    printf '%s\n' "${lines[@]}" > "$outdir/$f" || exit 
done 

Aは失敗したが、Pythonで若干良い試み:

import csv 
import json 

path_to_json = 'somedir/' 

json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')] 

print json_files # 

with open(json_files) as lookuplist: 
    # IT NEEDS to match the mediaID from the json FILENAME 
    with open('file1.csv', "r") as csvinput: 
     with open('VlookupOut','w') as output: 

      reader = csv.reader(lookuplist) 
      reader2 = csv.reader(csvinput) 
      writer = csv.writer(output) 

      d = {} 
      for xl in reader2: 
       d[xl[2]] = xl[3:] 

      for i in reader: 
       if i[4] in d: 
        i.append(d[i[4]]) 
       writer.writerow(i) 
+0

あなたの要件を解析するを使用しています不明IDに関係なく、jsonファイルのすべてのテキストが必要ですか? –

+0

正しい - IDは重要ではありません。ファイル名に従ってのみ一致する必要があります。私は少し明確にするためにOPを更新しました。 – Ycon

+0

あなたのCSVに実際にカンマの後ろにスペースがありますか? – webb

答えて

1

これは、あなたに必要な出力を提供します:

for file in /mediaid/*; do 
    while read -r entry fileid; do 
     jsonfile="$fileid.json" 
     if [[ -f "$jsonfile" ]]; then 
      text=$(jq -r 'map(.text) | join(", ")' "$jsonfile") 
      echo "$entry $fileid, $text" 
     fi 
    done < "$file" 
done > output.csv 

はJSONファイルに

+0

これはうまくいきませんでした。 .CSVファイルにすでに存在する行を結合する必要があります。 CSVファイルに印刷するだけではない – Ycon

+0

さらに説明してください。私はこの新しい要件を理解していません –

+1

すでに取り込まれた.CSVファイルに印刷されるJSONファイルの値を結合しようとしています – Ycon

関連する問題