【问题标题】:Turn response of bash command into serialized json string将 bash 命令的响应转换为序列化的 json 字符串
【发布时间】:2015-10-02 00:03:00
【问题描述】:

我需要在浏览器中打开 bash 命令的响应作为查询参数。

这个想法是从我的员工计算机上运行一个 bash 命令,并让它在我的新库存应用程序中打开一个 url,它会为我完成剩下的工作。

现在我只为连续剧工作。即:

inventoryme(){
  OUTPUT="$(system_profiler SPHardwareDataType | grep Serial)"
  open "http://localhost:3000/?serial=${OUTPUT}"
}

打开方式:http://localhost.dev:3000/?serial=%20%20%20%20%20%20Serial%20Number%20(system):CENSORED

我可以在我的网络应用程序端清楚地解析这个,或者在 bash 中做得更好,但我很想把 prsystem_profiler SPHardwareDataType 的整个响应变成一个 json 字符串!

有人对此有好的方法或建议吗?该命令返回如下内容:

 Model Name: MacBook Air
      Model Identifier: MacBookAir7,2
      Processor Name: Intel Core i7
      Processor Speed: 2.2 GHz
      Number of Processors: 1
      Total Number of Cores: 2
      L2 Cache (per Core): 256 KB
      L3 Cache: 4 MB
      Memory: 8 GB
      Boot ROM Version: MBA71.0166.B06
      SMC Version (system): 2.27f2
      Serial Number (system): CONSORED
      Hardware UUID: CONSORED

【问题讨论】:

  • 使用 awk 或类似名称。

标签: json bash serialization


【解决方案1】:

使用 Perl 的几种方法:

# JSON::PP should be available. JSON::XS is faster, but is not a core module
perl -MJSON::PP -ne '/(\S.*):\s*(.*)/ and $data{$1} = $2; END { print encode_json(\%data) }'

# If you don't have a JSON module installed
perl -ne '/(\S.*):\s*(.*)/ and $json .= "\"$1\": \"$2\","; END { chop $json; print "{ $json }" }'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-05
    • 2012-10-14
    • 1970-01-01
    • 2022-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多