簡単に言えば、私は2つのデータセットを結合しようとしています。私はgrep/bashまたはpythonを使用するために開いています。jsonファイルをvlookupと似たCSVと組み合わせる
読むディレクトリ/ MEDIAID
.jsonファイル名が.CSVで行と一致した場合におけるJSONファイルの内容をコピーし、
.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)
あなたの要件を解析するjqを使用しています不明IDに関係なく、jsonファイルのすべてのテキストが必要ですか? –
正しい - IDは重要ではありません。ファイル名に従ってのみ一致する必要があります。私は少し明確にするためにOPを更新しました。 – Ycon
あなたのCSVに実際にカンマの後ろにスペースがありますか? – webb