从 JSON 数组中去除换行符和引号,并通过 bash 将特定字符串设置为变量

0 bash sed jq

我有以下 JSON 数据:

{
    "Name": "No.reply",
    "邮箱": "no.reply@xxxxxx.com",
    “身份证”:5930,
    “细节”: 
    {
        "message": "您的姓名:john doe\n电子邮件:johndoe@xxxxxxx.com\n主题:我需要这方面的帮助\n描述:我可以找到手册的下载,但我只能找到适用于 Windows 或 Mac 的免费更新程序。你能帮我吗,因为我有一个 Chrome 笔记本和 Moto 智能手机。谢谢。John doe”
    }
}

顶层的姓名和电子邮件字段无关紧要,因为它们来自自动电子邮件。我需要的信息在消息字段和 ID 字段中,它与 John Doe 的信息相关。

无论如何,这就是我需要过滤的内容以及如何按此顺序将其保存到新文件中:

  • 名称:无论文本如何,它都应该读取此变量之后的行。
  • 邮箱:同上
  • 主题:同上
  • 说明:同上
  • ID:同上

因此,我需要删除引号、换行符,通过 bash 将这些特定字符串分配给变量,并读取这些字符串之后的内容。

我能够想出一些东西,但它不适用于此 JSON 输出:(仅当文本文件格式正确时才有效)

while IFS=''
do  case "$line" in
    "Name:"*)             uservar="${line#*: }" ;;
    "Email:"*)            emailvar="${line#*: }" ;;
    "Subject:"*)          subject="${line#*: }" ;;
    "Message:"*)          message="${line#*: }" ;;
    "ID:"*)        ticketidvar="${line#*: }" ;;
    esac
done <<-EOF
$(pbpaste)
EOF
Run Code Online (Sandbox Code Playgroud)

qub*_*ert 5

这假设Description: ...消息的一部分是单行,并且标头采用规范形式(不" subJECT :hey",请)。

它使用jq@sh格式规范以适合外壳的方式(带单引号)转义其输出。感谢@Stéphane Chazelas 的更正。

parse_json(){
  jq=$(jq -r '[.Email,.ID,(.details.message | split("\n")) | @sh] | join(" ")' -- "$1")
  eval "set -- $jq"
  email=$1; shift
  id=$1; shift
  for l; do
    case $l in
    "Your name: "*) name="${l#*: }";;
    "Subject: "*) subject="${l#*: }";;
    "Description: "*) description="${l#*: }";;
    # remove the following line if you want the .Email from json instead
    "Email: "*) email="${l#*: }";;
    esac
  done
  echo "id={$id}"
  echo "name={$name}"
  echo "email={$email}"
  echo "subject={$subject}"
  echo "description={$description}"
}

fz:/tmp% parse_json a.json
id={5930}
name={john doe}
email={johndoe@xxxxxxx.com}
subject={I need help with this}
description={I can find the download for the manual but I can only find the free updater for Windows or Mac. Can you help me please as I have a chrome notebook and Moto smart phone. Thank you. John doe
Run Code Online (Sandbox Code Playgroud)

case ... esac上面可以用的东西,将创建变量与相同的名称与非字母数字字符的头换成了下划线代替。这仅适用于支持${var//pat/repl}替换 ( bash, zsh, ksh93) 的shell :

parse_json(){
  jq=$(jq -r '[.Email,.ID,(.details.message | split("\n")) | @sh] | join(" ")' -- "$1")
  eval "set -- $jq"
  Email=$1; shift
  ID=$1; shift
  for l; do
    v="${l#*: }"; k="${l%%: *}"; eval "${k//[!a-zA-Z0-9]/_}=\$v"
  done
}

show_vars(){
  for v in ID Your_name Email Subject Description; do
    eval "echo \"$v=[\$$v]\""
  done
}

fz:/tmp$ parse_json a.json
fz:/tmp$ show_vars
ID=[5930]
Your_name=[john doe]
Email=[johndoe@xxxxxxx.com]
Subject=[I need help with this]
Description=[I can find the download for the manual but I can only find the free updater for Windows or Mac. Can you help me please as I have a chrome notebook and Moto smart phone. Thank you. John doe]
Run Code Online (Sandbox Code Playgroud)