tags:

views:

114

answers:

2

Is it "best practice" to use a GUID as a property name? (see sample JSON below)

{
    "ErrorType": 0,
    "I9e4f0477549111d997e0acd5cbb90d3f": {
        "statusCode": "0",
        "guid": "I9e4f0477549111d997e0acd5cbb90d3f",
        "moreProperties": "more values"
    },
    "N51D209F0505711DEA52DFAD621371B7C": {
        "statusCode": "0",
        "guid": "N51D209F0505711DEA52DFAD621371B7C",
        "moreProperties": "more values"
    }
}

I would assume no because now isn't the whole "object" part of JSON gone? You no longer have access to the namespace because the property name is random. And serializing (using JSON.NET) is no longer a one-liner.

Furthermore there is repeated data. The GUID is the name of the property and within that property is another object with a property name of "guid". Data normalization is not being considered.

I'm not writing this JSON just consuming it. If I was writing this JSON I would rewrite it to this:

{
    "ErrorType": 0,
    "guids": [
        {
            "statusCode": "0",
            "guid": "I9e4f0477549111d997e0acd5cbb90d3f",
            "moreProperties": "more values" 
        },
        {
            "statusCode": "0",
            "guid": "N51D209F0505711DEA52DFAD621371B7C",
            "moreProperties": "more values" 
        }
    ]
}

Thoughts?

+1  A: 

If you're searching for objects by GUID in Javascript, it's certainly better to use the GUID as a key, allowing you to write obj[someGuid].

Otherwise, it depends on the environment and usage; please provide more details.

SLaks
A: 

As SLaks points out, it depends on how you are trying to use the JSON. Given:

allObjects = {
    "ErrorType": 0,
    "I9e4f0477549111d997e0acd5cbb90d3f": {
        "statusCode": "0",
        "guid": "I9e4f0477549111d997e0acd5cbb90d3f",
        "moreProperties": "more values"
    },
    "N51D209F0505711DEA52DFAD621371B7C": {
        "statusCode": "0",
        "guid": "N51D209F0505711DEA52DFAD621371B7C",
        "moreProperties": "more values"
    }
}

myguid = "N51D209F0505711DEA52DFAD621371B7C";

you can simply access the data like allObjects[myguid]["moreProperties"]. If you generated the JSON as you suggest (without the guid as a key) and had to pull a value pertaining to a particular guid you would be forced to iterate over the array items and check for guid, like

for (var subObj in allObjects) {
    if (subObj['guid'] = myguid) {
        // you found it, store it and...
        break;
    }
}
sberry2A