Modifying Nested JSON

0 votes
asked Oct 28, 2024 in Question / help by Tassos
Hello all!

If I have a nested JSON

@startuml
!$testjson = {
    "A": {
        "A1": "val1",
        "A2": "val2",
        "B": {
            "B1": "val3",
            "B2": "val4",
            "C": {
                "C1": "val5",
                "C2": "val6"
            }
        },
        "D": {
            "D1": "val7",
            "D2": "val8"
        }
    }
}
@enduml

is there a nice way of using the JSON commands to be able to add a key value pair at any given level of nesting?

such as (example with python style notation)

$testjson["A"]["B"]["C"]["E"] = "eee"

$testjson["A"]["B"]["F"] = "fff"

I have played around with combinations of %json_add, %json_set, and %json_merge but I can't figure out how to properly use them beyond single nested JSON

I have been able to get some nested modification to work but in really hacky ways that erases nested JSON for adjacent keys to the key path that I am trying to modify

Any help is appreciated Thank you :)

1 Answer

0 votes
answered Oct 28, 2024 by The-Lu (87,240 points)

Hello T.,

FYI PlantUML use the `minimal-json` library;
and it doesn't have all the features but enough to do what you want.... (with intermediate variables), as:

@startuml
!$testjson = {
    "A": {
        "A1": "val1",
        "A2": "val2",
        "B": {
            "B1": "val3",
            "B2": "val4",
            "C": {
                "C1": "val5",
                "C2": "val6"
            }
        },
        "D": {
            "D1": "val7",
            "D2": "val8"
        }
    }
}

!$e = {"A":{"B":{"C":{"E":"eee"}}}}

json e_JSON_set_by_var %json_set($testjson, $e)
json e_JSON_set_by_str %json_set($testjson, %str2json('{"A":{"B":{"C":{"E":"eee"}}}}'))

!$f = {"A":{"B":{"F":"ff"}}}

json f_JSON_set_by_var %json_set($testjson, $f)
json f_JSON_set_by_str %json_set($testjson, %str2json('{"A":{"B":{"F":"ff"}}}'))
@enduml

See also doc. here:

Enjoy,
Regards,
Th.

commented Oct 28, 2024 by Tassos
Thank you very much! :)
...