问题
I am trying to apply a JDT transform to a JSON document in order to modify a property in a N-th array element. Is that possible without having to replace the entire element or even the entire array?
{
"array": [
{
name: "A",
value: 0
},
{
name: "B",
value: 3.14
}
]
}
Is there a transform that gets me to the following? I want to alter the 2nd array element and only its "value" property. I don't want to search for it by "name" but rather access by index.
{
"array": [
{
name: "A",
value: 0
},
{
name: "B",
value: 12345678
}
]
}
回答1:
The challenge
It is easy to do your transform with some libraries in JSON. If your object is called foo
, you mainly want to something like foo.array[1].value = "12345678"
without any kind of looping.
The JDT way
I found How to use SlowCheetah to transform an array elements in Json config file? which asks
For example, if my base config file has this setting:
{ "Settings" : [1, 2, 3] }
and I want to transfer it to:
{ "Settings" : [4, 5, 6] }
The solution by Collin K was
{ "@jdt.replace": { "@jdt.path": "$.Settings", "@jdt.value": [4,5,6] } }
This seems like you need to actually replace the whole array.
Digging further let me to an open issue of JDT which seems to confirm this assumption.
Disclaimer
I have not used JDT myself, but I have been struggling with nested JSONs of various kinds e.g. with Elasticsearch.
Further references
- https://github.com/microsoft/json-document-transforms/wiki/Replace-Transformation
- Using jq to update objects within a JSON document if the value corresponding to a given key starts with a specified string - the JQ way I would use
来源:https://stackoverflow.com/questions/61780767/jdt-transform-to-modify-n-th-array-element