【问题标题】:Nested JSON to CSV using JQ使用 JQ 将 JSON 嵌套到 CSV
【发布时间】:2019-11-27 01:06:51
【问题描述】:

我正在尝试将此 json https://pastebin.com/1ch1CzM4 转换为 csv,以便将其全部导入数据库,但我一直遇到错误。我得到的最接近的是

./jq -r '[.[]] | @csv'

但是这并没有起到作用,因为它是嵌套的。非常感谢任何帮助。

我试图让父母作为第一行,所以“地址、舒适组、check_in_time、check_out_time”,然后如果其中有一个 json,它只是 csv 中的一个平面 json 文本。

如果我尝试

jq -r '[[.address, .amenity_groups, .check_in_time, .check_out_time] | map(tostring) | @csv] | map(tostring) | @csv'

那么输出就是

"""140 Ancien Chemin De Berre, Lambesc"",""[{""""amenities"""":[""""Garden"""",""""Terrace""""],""""group_name"""":""""General""""}]"",""16:00:00"",""10:00:00"""

vs 想要的

address, amenity_groups, check_in_time, check_out_time
$json_of_address, $json_of_amenity_groups, 12, 12

【问题讨论】:

标签: json nested export-to-csv jq


【解决方案1】:

似乎满足所述要求的解决方案是:

[.address, .amenity_groups, .check_in_time, .check_out_time]
| map(tostring)
| @csv

您可能希望避免盲目使用tostring,但至少它是通用的。

通用 JSON 到 CSV 转换

用于将任意 JSON 对象数组转换为 CSV 的 jq 过滤器 (json2csv) 位于:

jq: Object cannot be csv-formatted, only array

使用您的 JSON 对象流,您可以(例如)通过 -s 命令行选项像这样使用它:

map({address, amenity_groups, check_in_time, check_out_time})
| json2csv
使用 json2csv 输出
"address","amenity_groups_0_amenities","amenity_groups_0_group_name","amenity_groups_1_amenities","amenity_groups_1_group_name","amenity_groups_2_amenities","amenity_groups_2_group_name","amenity_groups_3_amenities","amenity_groups_3_group_name","amenity_groups_4_amenities","amenity_groups_4_group_name","amenity_groups_5_amenities","amenity_groups_5_group_name","check_in_time","check_out_time"
"140 Ancien Chemin De Berre, Lambesc","Garden|Terrace","General","null","null","null","null","null","null","null","null","null","null","16:00:00","10:00:00"
"Tayside Farm 1077, East London","Garden|Smoking allowed in bedrooms|Patio","General","Fridge|Kitchen","Meals","Parking","Parking","Beach/pool towels","Pool and beach","TV|Shower","Rooms","Iron and board","Room Amenities","14:00:00","12:00:00"

【讨论】:

  • 它真的很接近,但它给了我一些奇怪的输出。如果你有时间,我很乐意让你看看。这让我发疯了
  • 在你的 Q 更新中,你调用了两次 map(tostring) 并使用了两次 @csv!
猜你喜欢
  • 2020-05-06
  • 2022-11-02
  • 2017-11-28
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多