Json formatting/style doesn't seem to be respected when adding values/members
dpozinen opened this issue · comments
Dariy Pozinenko commented
What version of OpenRewrite are you using?
- OpenRewrite 2.12.0
- Maven plugin 5.23.3
Context
I have created a recipe that adds key+value into a json. It is done via Json.Literal
and is inspired by json.ChangeValue
. Here's the relevant code:
JsonRightPadded<JsonKey> newKey = new JsonRightPadded<>(
new Json.Literal(randomId(), Space.EMPTY, Markers.EMPTY, "\"" + key + "\"", key),
Space.EMPTY,
Markers.EMPTY
);
Json.Literal newValue = new Json.Literal(randomId(), Space.build(" ", emptyList()), Markers.EMPTY, value, unQuote(value));
Json newMember = new Json.Member(randomId(), space, Markers.EMPTY, newKey, newValue);
List<Json> members = jsonIsEmpty ? new ArrayList<>() : obj.getMembers();
members.add(newMember);
return obj.withMembers(members);
Problem
- I don't seem to be able to control the padding after the value is inserted
- If this isn't the only value in the object, the automatic insertion of the comma is on its own line.
My test:
...
rewriteRun(
spec -> spec.recipe(new AddKeyValue(
"$.", "key", "\"val\""
)),
//language=json
json("""
{
"l": [ 1, 2 ]
}
""",
"""
{
"l": [ 1, 2 ],
"key": "val"
}
""")
);
...
fails with:
expected:
"{
"l": [ 1, 2 ],
"key": "val"
}"
but was:
"{
"l": [ 1, 2 ]
,
"key": "val"}"
The same thing happens with Arrays and their Values.
Expected Behaviour
Can be seen in the test failure:
- When adding an element the comma is added on the same line as the previous element.
- The closing bracket is not moved from it's initial position
In general I think this is a styling issue, which I understand is not supported for json? I could not find any json.style.*
classes, pretty sure TabsAndIndentsStyle
for xml solves this issue. CMIIW. Thanks 🙂