如何从同一个json文件中获取两个行值,并在另一个文件中并列显示?

问题描述 投票:-1回答:1

example_json_file。

{
        "href": "/users/115",
        "id": 115,
        "username": "test",
        "locked": false,
        "type": "local",
        "effective_groups": 
}

假设我们在一个文件里有很多这样的值。grep '"id"'

It helps to grep individual field values. However, I need help in merging two field values like ID and USERNAME and put them in a separate file with comma separated values using a single command.

expected output

test,115

example_json_file: { "href": "
json awk sed grep
1个回答
1
投票

与有效的JSON和 jq:

jq -r '"\(.id),\(.username)"' file

输出:

115,测试

0
投票

这就需要Ed. 如果我们假设每个JSON集都有相同数量的值线;我知道我们可能不应该这样做,那么... ...

#!/bin/sh

cat >> edchop+.txt << EOF
1,8W temp
1,8d
wq
EOF

while [ $(wc -l example_json_file | cut -d' ' -f1) -gt 0 ]
do
  ed -s example_json_file < edchop+.txt
  name=$(sed -n '/username/p' temp | cut -d':' -f2 | tr -d ' ' | tr -d ',' | tr -d '\"')
  id=$(sed -n '/id/p' temp | cut -d':' -f2 | tr -d ' ' | tr -d ',')
  echo -e "${name}","${id}" >> example_csvfile
done

rm -v ./edchop+.txt
rm -v ./temp
© www.soinside.com 2019 - 2024. All rights reserved.