Json

如何從編碼的 JSON 對像中提取欄位

  • October 14, 2020

您好我正在嘗試從以下 JSON 數據中提取令牌last_namefirst_name``phone

{"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2167,\"id\":95384129,\"access_hash\":\"780828213343231334\",\"first_name\":\"xaa\",\"last_name\":\"xz\",\"phone\":\"989123930793\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"409671715068685579\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"455930331\",\"local_id\":281464,\"secret\":\"3283911659027961987\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"455930331\",\"local_id\":281466,\"secret\":\"3533047346646019161\"}},\"status\":{\"_\":\"userStatusLastMonth\"}}","phone":"989123930793","@version":"1","typ":"tg_contacts","access_hash":"780828213343231334","id":95384129,"@timestamp":"2020-01-26T13:53:31.091Z","path":"/home/user/mirror2/users_5d3de570e549953b6163eb0f.log","type":"redis","flags":2167,"host":"ubuntu","imported_from":"tg"}

這是我的命令

jq -r '[.first_name, .last_name, .phone]|@csv'

我怎麼只能提取phone欄位,我不知道為什麼我不能提取first_namelast_name.

如果你試試

jq -r '.' file.json

你會看到沒有名字和姓氏,只有電話。

{
 "message": "{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2167,\"id\":95384129,\"access_hash\":\"780828213343231334\",\"first_name\":\"xaa\",\"last_name\":\"xz\",\"phone\":\"989123930793\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"409671715068685579\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"455930331\",\"local_id\":281464,\"secret\":\"3283911659027961987\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"455930331\",\"local_id\":281466,\"secret\":\"3533047346646019161\"}},\"status\":{\"_\":\"userStatusLastMonth\"}}",
 "phone": "989123930793",
 "@version": "1",
 "typ": "tg_contacts",
 "access_hash": "780828213343231334",
 "id": 95384129,
 "@timestamp": "2020-01-26T13:53:31.091Z",
 "path": "/home/user/mirror2/users_5d3de570e549953b6163eb0f.log",
 "type": "redis",
 "flags": 2167,
 "host": "ubuntu",
 "imported_from": "tg"
}

您要查找的欄位位於 中.message,這是一個字元串,一個編碼的 JSON 對象

jq具有fromjson您可以使用並將其作為 JSON 獲取的內置函式:

jq -r '.message | fromjson | [.first_name, .last_name, .phone]|@csv' file.json
"xaa","xz","989123930793"

引用自:https://unix.stackexchange.com/questions/614238