Given the following JSON...
{
"metadata": {
"id": "1234",
"type": "file",
"length": 395
}
}
... how do I convert it to
{
"metadata.id": "1234",
"metadata.type": "file",
"metadata.length": 395
}
Tx.
Given the following JSON...
{
"metadata": {
"id": "1234",
"type": "file",
"length": 395
}
}
... how do I convert it to
{
"metadata.id": "1234",
"metadata.type": "file",
"metadata.length": 395
}
Tx.
This is definitely not trivial, but possible by trying to flatten it recursively. I haven't tested this thoroughly, but it works with your example and some other basic one's I've come up with using arrays:
JsObject
has thefieldSet
method that returns aSet[(String, JsValue)]
, which I mapped, matched against theJsValue
subclass, and continued consuming recursively from there.You can use this example by passing a
JsValue
toapply
:We'll leave it as an exercise to the reader to make the code more beautiful looking.
Here's my take on this problem, based on @Travis Brown's 2nd solution.
It recursively traverses the json and prefixes each key with its parent's key.
which turns this:
into this:
@Trev has the best solution here, completely generic and recursive, but it's missing a case for array support. I'd like something that works in this scenario:
turn this:
into this:
I've arrived at this, which appears to work, but seems overly verbose. Any help in making this pretty would be appreciated.
You can do this pretty concisely with Play's JSON transformers. The following is off the top of my head, and I'm sure it could be greatly improved on:
And then:
And:
Just change the path if you want to handle
metadata
fields somewhere else in the tree.Note that using a transformer may be overkill here—see e.g. Pascal Voitot's input in this thread, where he proposes the following:
It's not as composable, and you'd probably not want to use
as
in real code, but it may be all you need.Based on previous solutions, have tried to simplify the code a bit
Thanks m-z, it is very helpful. (I'm not so familiar with Scala.)
I'd like to add a line for "flatten" working with primitive JSON array like "{metadata: ["aaa", "bob"]}".