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

将输入JSON转换为两个共享相同属性的不同集合结构

JSON结构转换需求

需要把输入的JSON转换成包含两个顶级键的JSON结构,两个键对应的对象完全复用输入JSON的所有属性。

示例输入

{
  "name": "XYZ",
  "lastName": "PQR",
  "address": "abc, mnop, 534291"
}

预期输出

{
  "employee": {
    "name": "XYZ",
    "lastName": "PQR",
    "address": "abc, mnop, 534291"
  },
  "address": {
    "name": "XYZ",
    "lastName": "PQR",
    "address": "abc, mnop, 534291"
  }
}

实现方式

Python 版本

直接复用输入对象的引用(内存中为同一个实例):

import json

# 输入JSON字符串
input_json = '''{
  "name": "XYZ",
  "lastName": "PQR",
  "address": "abc, mnop, 534291"
}'''

# 解析为字典
input_data = json.loads(input_json)

# 构建输出结构
output_data = {
    "employee": input_data,
    "address": input_data
}

# 输出格式化后的JSON
print(json.dumps(output_data, indent=2))

如果需要独立对象(避免修改其中一个影响另一个),使用深拷贝:

import json
import copy

input_json = '''{
  "name": "XYZ",
  "lastName": "PQR",
  "address": "abc, mnop, 534291"
}'''

input_data = json.loads(input_json)

output_data = {
    "employee": copy.deepcopy(input_data),
    "address": copy.deepcopy(input_data)
}

print(json.dumps(output_data, indent=2))

JavaScript 版本

直接复用引用:

const inputData = {
  "name": "XYZ",
  "lastName": "PQR",
  "address": "abc, mnop, 534291"
};

const outputData = {
  employee: inputData,
  address: inputData
};

console.log(JSON.stringify(outputData, null, 2));

深拷贝版本(适合复杂嵌套对象):

const inputData = {
  "name": "XYZ",
  "lastName": "PQR",
  "address": "abc, mnop, 534291"
};

// 通过JSON序列化反序列化实现深拷贝
const outputData = {
  employee: JSON.parse(JSON.stringify(inputData)),
  address: JSON.parse(JSON.stringify(inputData))
};

console.log(JSON.stringify(outputData, null, 2));

内容的提问来源于stack exchange,提问作者Prasad S Deshpande

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:22:32