You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jq向已有JSON对象中添加空对象

解决方案

给JSON的disk字段添加键为/dev/sda的空对象,本质和添加普通键值对逻辑一致,只是把值设为空对象{}即可。以下是两种常用编程语言的实现示例:

Python 实现

import json

# 输入JSON字符串
input_json = '''{
  "ver" : "2.4",
  "startDate"  : "2022-12-07T10:38:10+07:00",
  "disk" : {},
  "network" : {
    "ipv4" : {},
    "ipv6" : {}
  },
  "test" : {}
}'''

# 解析为Python字典
data = json.loads(input_json)
# 给disk字段添加指定键的空对象
data["disk"]["/dev/sda"] = {}
# 转换为带缩进的格式化JSON
output_json = json.dumps(data, indent=4)

print(output_json)

JavaScript 实现

const inputJson = `{
  "ver" : "2.4",
  "startDate"  : "2022-12-07T10:38:10+07:00",
  "disk" : {},
  "network" : {
    "ipv4" : {},
    "ipv6" : {}
  },
  "test" : {}
}`;

// 解析为JavaScript对象
const data = JSON.parse(inputJson);
// 给disk字段添加指定键的空对象
data.disk["/dev/sda"] = {};
// 转换为带缩进的格式化JSON
const outputJson = JSON.stringify(data, null, 4);

console.log(outputJson);

核心步骤:将JSON解析为可操作的字典/对象 → 给目标字段的指定键赋值空对象{} → 转回格式化后的JSON。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:55:25