LoginSignup
0
0

More than 3 years have passed since last update.

jqでcsv変換する前にjsonの中のカンマを削除する

Last updated at Posted at 2019-09-10

やりたいこと

jsonファイルをcsvにして使用している。
csvにしたデータをawkでいじろうとしたとき、区切り文字以外にデータの中身にカンマがあり、うまく処理できない。
jsonファイルの中にあるカンマを削除する

テストファイル

test.json
[
 {
  "id": "1",
  "text": "text1 , test1"
 },
 {
  "id": "2",
  "text": "text2 , test2"
 }
[

jqのgsub→失敗

tostringで配列が崩れて、@csvができなくなってしまう。

# cat test.json | jq '.[]|tostring|gsub(",";"comma")'
 "{\"id\": \"1\"comma\"text\": \"text1 comma test1\"}"
 "{\"id\": \"2\"comma\"text\": \"text2 comma test2\"}"

結局sedに頼る

分かりやすさのため、下記の例ではカンマ除去は削除ではなく、commaに変更している
カンマ除去の確認

# cat test.json | sed s/[^\"|^\}],/comma/g
[
 {
  "id": "1",
  "text": "text1 comma test1"
 },
 {
  "id": "2",
  "text": "text2 comma test2"
 }
[

CSV変換

# cat test.json | sed s/[^\"|^\}],/comma/g| jq -r '.[]|[.id, .text]|@csv'
"id": "1","text": "text1 comma test1"
"id": "2","text": "text2 comma test2"
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0