I am using the JayWay JsonPath to manipulate JSON objects.
I want to insert a JSON object into a JSON array:
### before
{
"students": []
}
### after
{
"students": [{"id": 1, "name": "Bob"}]
}
Somehow I cannot accomplish this in JsonPath. If I add the object as a string, it is not recognized as a JSON object:
var context = JsonPath.parse("{\"students\": []}");
context.add("students", "{\"id\": 1, \"name\": \"Bob\"}");
System.out.println(context.jsonString());
// > {"students":["{\"id\": 1, \"lastName\": \"Bob\"}"]}
If I try to parse the object, JsonPath adds an empty object:
var context = JsonPath.parse("{\"students\": []}");
context.add("students", JsonPath.parse("{\"id\": 1, \"name\": \"Bob\"}"));
System.out.println(context.jsonString());
// > {"students":[{}]}
How can I insert the JSON object into the array?
Use .json()
method:
var context = JsonPath.parse("{\"students\": []}");
Object entryToAdd = JsonPath.parse("{\"id\": 1, \"name\": \"Bob\"}").json();
String updatedJson = context.add("students", entryToAdd).jsonString();
System.out.println(updatedJson);
prints
{"students":[{"id":1,"name":"Bob"}]}