3

Is there a reason to encode options like this:

{
    "options":[
        {
            "name":"opt1",
            "value":"val1",
        },
        {
            "name":"opt2",
            "value":"val2",
        },
        {
            "name":"opt3",
            "value":"val3",
        }
    ]
}

instead of like this:

{
    "options":{
        "opt1":"val1",
        "opt2":"val2",
        "opt3":"val3"
    }
}

I regularly see this pattern in both JSON and XML, what is the reason for doing things this way? The only advantage I can see is that the first way would allow duplicate option names, which is usually not relevant.

9
  • 4
    Both can be reasonable, but the first variant is more general. It supports duplicates, non-string keys, and maintains the order of elements. It might also be easier to deserialize for some systems.
    – amon
    Sep 26, 2023 at 4:57
  • The first mode is auto-serialized and auto-deserialized by a lot of tools. The second one isn't.
    – T. Sar
    Sep 26, 2023 at 17:03
  • 3
    The first also allows additional attributes for example you want to add a "type" to the options.
    – DavidT
    Sep 26, 2023 at 17:23
  • 1
    @T.Sar You dont have an array of names. You have an array of key-value pairs except the keys are the values of a key-value pair with key “name” and the values are the values of a key-value pair wit key “value”. If that sounds confusing, that’s because it is.
    – gnasher729
    Sep 26, 2023 at 20:58
  • 1
    @T.Sar Can I ask what tooling you use that doesn't support the second? It sounds pretty unfortunate.
    – JimmyJames
    Oct 27, 2023 at 20:07

2 Answers 2

1

I would rather go with the 1st way. The reason is that when I look at the object that is getting serialized, by having a quick look I would want to get how it looks. In the first way, everything is defined so that you know which type of field it is and everything just by looking at the POJO/Object definition. 2nd way, I wouldn't know what keys are there and I definitely can't see that from looking at the object and would want an example JSON there. I also think the first way would also help with better documentation. Also, the first way is extensible if you want to add metadata along with key and value. Go with 2nd way only if you are sure you don't need to add a new field to a key-value pair

-1

The first one is totally unreasonable to store a list of key-value pairs. It’s the style that the word “enterprisy” was invented for: Why do it the easy way if you can do it the hard way instead.

Not the answer you're looking for? Browse other questions tagged or ask your own question.