You need to enable JavaScript to run this app. 原生macOS下使用bash脚本将命令输出转换为合法JSON对象的方法
优惠活动
大模型
产品
解决方案
定价
更多

原生macOS下使用bash脚本将命令输出转换为合法JSON对象的方法

原生macOS下diskutil输出转JSON方案

方案1:基于plist+plutil实现(更稳定,推荐)

你之前的plist方案存在使用误区,plutil完全支持标准输入作为数据源,且输出为标准ECMA-404规范JSON,无需临时文件:

# 直接将diskutil的plist输出通过管道传给plutil转JSON
diskutil info -plist /dev/disk2 | plutil -convert json -o - -

参数说明:

  • -o - 指定输出到标准输出
  • 末尾的- 代表从标准输入读取plist内容

如果需要格式化输出更易读,可以搭配系统自带的python3( macOS 10.15+ 原生自带)做美化:

diskutil info -plist /dev/disk2 | plutil -convert json -o - - | python3 -m json.tool

方案2:直接解析「键: 值」文本输出(适配无plist参数的命令通用场景)

用系统自带awk处理键值提取、转义、JSON拼接,自动处理值里的双引号转义,适配带空格、特殊字符的键名/值:

diskutil info /dev/disk2 | awk '
BEGIN {
    printf "{"
    first = 1
}
# 匹配每行「键: 值」格式,拆分键和值
/^[[:print:]]+:[[:space:]]/ {
    if (!first) printf ","
    first = 0
    # 拆分冒号左右的键和值
    split($0, parts, /:[[:space:]]/, seps)
    key = parts[1]
    # 处理值中可能存在的冒号,把剩余部分拼接为完整值
    value = substr($0, length(key) + length(seps[1]) + 1)
    # 转义值中的双引号
    gsub(/"/, "\\\"", value)
    # 输出键值对
    printf "\"%s\":\"%s\"", key, value
}
END {
    printf "}\n"
}'

如果需要格式化输出,同样可以追加| python3 -m json.tool。

内容的提问来源于stack exchange,提问作者RipSaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 06:27:03