user468311
user468311

Reputation:

Is it ok to have JSON objects with varying number of attributes?

I am designing an API resonse for my mobile app right now, and response should contain array of operations. Some of them might have all attributes, some may not, see the example:

{
"operations":[
        {
            "type":"0",
            "location":"01"
        },
        {
            "type":"1",
            "location":"1234"
            "item_id":"",
            "item_name":"Item A",
        }
    ]
}

Is that a good way, or should I reconsider my design? I mean the varying number of attribues. Thank you!

Upvotes: 0

Views: 208

Answers (2)

xgoodvibesx
xgoodvibesx

Reputation: 3

It depends on the code you'll be writing to handle the object :) As long as you write your code to handle missing elements you'll be fine.

Javascript couldn't give a hoot if an object in an array matches the structure of the other objects or not, if that's what you're concerned about.

p.s: Watch those comma's! They cause me more grief than anything else :p IE will break on a trailing comma :(

Upvotes: 0

zzlalani
zzlalani

Reputation: 24384

Although It will be good for the bandwidth to keep the attributes out of the json string that doesn't have values. But I will suggest you to keep it other way, either send null or empty string "" it will be help at the decoding side

{
"operations":[
        {
            "type":"0",
            "location":"01"
            "item_id":null,
            "item_name":null,
        },
        {
            "type":"1",
            "location":"1234"
            "item_id":"",
            "item_name":"Item A",
        }
    ]
}

Upvotes: 1

Related Questions