我正在尝试在JSON中添加一个新元素,但是我没有正确完成此操作。
我已经尝试了很多方法,不确定是怎么回事。
输入JSON
{
"UnitID":"1148",
"UNIT":"202B",
"Speed":"29.0",
"SpeedMeasureValue":"MPH",
"Direction":"212",
"LatitudeY":"42.0474150666667000",
"LongitudeX":"-88.2750256000000000",
"TimeStamp":"2019-04-25 15:19:45.0300000",
"Status":"Enroute","StatusID":"13",
"CallID":"841809",
"ORI":"IL0450600"
}
连接后需要JSON输出
{
"UnitID":"1148",
"UNIT":"202B",
"Speed":"29.0",
"SpeedMeasureValue":"MPH",
"Direction":"212",
"LatitudeY":"42.0474150666667000",
"LongitudeX":"-88.2750256000000000",
"TimeStamp":"2019-04-25 15:19:45.0300000",
"Status":"Enroute","StatusID":"13",
"CallID":"841809","ORI":"IL0450600",
"association": [
{
"event": "123",
"label": "",
"relation": "321"}
]
}
代码-将objectToJson
视为输入JSON的数组,并将obj
作为前面提到的输入json
objectToJson.forEach((obj: any) => {
const association: any = `"association": [{"event": 123, "label": "", "relation": "321"}]`;
const concatenatedObject: object = Object.assign(obj, association);
const concatEventsJson: any = JSON.stringify(concatenatedObject);
console.log(concatEventsJson);
}
答案 0 :(得分:1)
只需将association
属性添加到对象-您需要通过以下方式将association
设置为变量(而不是字符串):
const association: any = [{"event": 123, "label": "", "relation": "321"}];
const concatenatedObject: object = { ...obj, association };
演示:
const objectToJson = [{"UnitID":"1148","UNIT":"202B","Speed":"29.0","SpeedMeasureValue":"MPH","Direction":"212","LatitudeY":"42.0474150666667000","LongitudeX":"-88.2750256000000000","TimeStamp":"2019-04-25 15:19:45.0300000","Status":"Enroute","StatusID":"13","CallID":"841809","ORI":"IL0450600"}];
objectToJson.forEach((obj) => {
const association = [{"event": 123, "label": "", "relation": "321"}];
const concatenatedObject = { ...obj, association };
console.log(concatenatedObject);
});
.as-console-wrapper { max-height: 100% !important; top: auto; }