我正在尝试将一个元素附加到数组中。但我无法确保数组已存在。所以如果没有它应该被创建。
此示例有效:
来源json:
{
"data": []
}
补丁文档:
[{
"op":"add",
"path":"/data/-",
"value": "foo"
}]
但在这种情况下,它不会附加任何内容:
来源json:
{}
我尝试了一个解决方案,首先添加一个空数组然后追加,但这将始终清除现有条目:
[{
"op":"add",
"path":"/scores",
"value": []
},
{
"op":"add",
"path":"/scores/-",
"value": {
"time":1512545873
}
}]
我是否遗漏了某些内容,或者在规范中没有解决方案?
答案 0 :(得分:2)
很高兴看到你使用fast-json-patch。我维护这个lib。
我想说你可以通过纯JSON补丁实现这一目标。你的JS需要一些逻辑。如下所示:
var doc = {};
var patch = [{
"op": "add",
"path": "/scores/-",
"value": {
"time": 456
}
}];
var arr = jsonpatch.getValueByPointer(doc, '/scores');
if (!arr) {
jsonpatch.applyOperation(doc, {
"op": "add",
"path": "/scores",
"value": []
});
}
var out = jsonpatch.applyPatch(doc, patch).newDocument;
pre.innerHTML = JSON.stringify(out);

<script src="https://cdnjs.cloudflare.com/ajax/libs/fast-json-patch/2.0.6/fast-json-patch.min.js"></script>
<pre id="pre"></pre>
&#13;
答案 1 :(得分:0)
在Openshift中,您可以使用以下命令执行此操作:
structure(list(x_NMI = c(6347, 6347), EstimateReadBitmaskInd = c(0,
0), MeterRegActiveReadingDt = c("15-01-2013", "18-01-2013"),
MtrRgActNetEngyMaxdlyKwh = c(0.831,
0.65), RegisterId = c(2, 2), RegisterType = c(2, 2), Building = c(6,
6), numberofpeople = c(5, 5), pool = c(2, 2), typeofAC = c(1,
1), NoOfAc = c(1, 1)), row.names = 1:2, class = "data.frame")