从文本文件中嵌入的 JSON 文档中提取字段

从文本文件中嵌入的 JSON 文档中提取字段

我有以下文本行,我需要从该文本行的 JSON 部分中提取一些字段。

June 27th 1997, 10:11:52.621 {"serviceId":"00034","AccessKey":"SBCDSCB","trackID":"KOLPSLSLSLL99029283","membersId":"TEST_0002930493","shopperInfo":{"emailid":"[email protected]"},"parkid":{"parkssID":"carrier-park"},"cartinfo":{"checkType":"preorder","detailsmetis":"card","currency":"US","grosscount":"10","reedeem":".00","discount":".00","tokenvalue":{"token":"11102020392023920920393993","bin":"00000000","digit":"0000","expirationDate":"202209","price":"10"}},"cartdetails":[{"dones":[{"donesnames":"test","price":"003","qunt":"1"}]}]}

我需要的输出如下:

serviceId,trackID,currency,grosscount 
00034,KOLPSLSLSLL99029283,US,10

请建议获得上述结果的方法。

我尝试使用该awk命令和一些sed相关查询,但无法让它工作。

答案1

使用jq

echo "serviceId,trackID,currency,grosscount"
cut -d' ' -f5- < file \
| jq -r '[.serviceId, .trackID,.cartinfo.currency,.cartinfo.grosscount] | @csv'

除了@csv使用 ,还可以使用在字段周围添加引号paste

echo "serviceId,trackID,currency,grosscount"
cut -d' ' -f5- < file \
| jq -r '.serviceId, .trackID,.cartinfo.currency,.cartinfo.grosscount' \
| paste -sd,

答案2

假设 JSON 的结构与嵌入的 JSON 文档相同你的另一个问题, 我们可以用jq我在那里提出的相同命令

jq -r '
    [ "serviceId", "trackID", "currency", "grosscount" ],
    [ .serviceId, .trackID, .cartinfo.currency, .cartinfo.grosscount ] |
    @csv'

{这里唯一缺少的是在第一个在线数据之前删除非 JSON 数据的东西。我们可以这样做sed

sed 's/^[^{]*//' file |
jq -r '
    [ "serviceId", "trackID", "currency", "grosscount" ],
    [ .serviceId, .trackID, .cartinfo.currency, .cartinfo.grosscount ] |
    @csv'

鉴于问题中的数据,这将产生

"serviceId","trackID","currency","grosscount"
"00034","KOLPSLSLSLL99029283","US","10"

相关内容