迭代json数组项

x0fgdtte  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(94)

我想寻求帮助。JSON数组我怎样才能使迭代数组分割后,并创建csv输出
我的意见是...

[
    {
        "body": [
            {
                "title": "topinfo",
                "longText": "item1|details item 1|details sdfdfdfd ||details gbgfgghmhjmh||details 5348786"
            },
            {
                "title": "topinfo",
                "longText": "item2|details item 2|details sdfdfdfd ||details gbgfgghmhjmh||details 9784561"
            }
            ]
    }
]

字符串
其实我打电话给jq..

jq '.[] | [.body[] | {longText,title} ] | to_entries | map( (.value.level = "\(1+.key)" ) | .value) | .[] | [.title,.level,(.longText|split("|"))] '


实际结果

[
  "topinfo",
  "1",
  [
    "item1",
    "details item 1",
    "details sdfdfdfd",
    "details gbgfgghmhjmh",
    "details 5348786"
  ]
]
[
  "topinfo",
  "2",
  [
    "item2",
    "details item 2",
    "details sdfdfdfd",
    "details gbgfgghmhjmh",
    "details 9784561"
  ]
]


我希望这个CSV...

topinfo;1;1;item1
topinfo;1;2;details item 1
topinfo;1;3;details sdfdfdfd
topinfo;1;4;details gbgfgghmhjmh
topinfo;1;5;details 5348786

topinfo;2;1;item2
topinfo;2;2;details item 2
topinfo;2;3;details sdfdfdfd
topinfo;2;4;details gbgfgghmhjmh
topinfo;2;5;details 9784561

r9f1avp5

r9f1avp51#

嵌套迭代和变量绑定:

.[].body                                                   # top-level iteration
| to_entries[] as {key: $i, value: {$title, $longText}}    # collect values
| $longText / "|"                                          # split at "|"
| map(select(. != ""))                                     # remove empty items(?)
| (                                                        # open grouping context
    to_entries[] as {key: $j, $value}                      # collect values
    | [$title, $i+1, $j+1, $value]                         # prepare output line
    | join(";")                                            # join to string
  ), ""                                                    # add empty line

个字符
Demo
要正确转义CSV输出,请使用@csv而不是join(";")。请注意,这将通过逗号而不是分号“连接”,并在必要时引用项目:

"topinfo",1,1,"item1"
"topinfo",1,2,"details item 1"
"topinfo",1,3,"details sdfdfdfd "
"topinfo",1,4,"details gbgfgghmhjmh"
"topinfo",1,5,"details 5348786"

"topinfo",2,1,"item2"
"topinfo",2,2,"details item 2"
"topinfo",2,3,"details sdfdfdfd "
"topinfo",2,4,"details gbgfgghmhjmh"
"topinfo",2,5,"details 9784561"


Demo

相关问题