NeilMonday
NeilMonday

Reputation: 2730

Can JSON Object Attribute Names Be Integers?

I am just getting started with some Jackson JSON data here. This section is giving me trouble.

"pointData":{
    "1":"32.1093904, 66.7065216", 
    "2":"33.1236854, 67.8128443", 
    "3":"32.9524550, 67.0013501"
}

It seems to me that having integers as the attribute name is illegal. Is this correct?

Upvotes: 4

Views: 6172

Answers (2)

Jonathan M
Jonathan M

Reputation: 17451

You're correct that JSON cannot have integer attribute names, because all JSON attribute names must be quoted as yours are above, making them strings. See the flow here: http://json.org/

Also, your JSON structure above is invalid because it begins with an attribute name, but no object that the attribute is a part of. If you're getting errors, this is why. A legal structure would be:

{"pointData":{
    "1":"32.1093904, 66.7065216", 
    "2":"33.1236854, 67.8128443", 
    "3":"32.9524550, 67.0013501"
    }
}

FYI, if you're storing point data, a perhaps better structure would be:

{"pointData":{
    "1": {"x": 32.1093904, "y": 66.7065216}, 
    "2": {"x": 33.1236854, "y": 67.8128443}, 
    "3": {"x": 32.9524550, "y": 67.0013501}
    }
}

Notice two things about this structure:

  1. Each point has an x and y property that are independently accessible.
  2. The values of the x and y properties are numeric, not strings.

Upvotes: 7

Jordan Running
Jordan Running

Reputation: 106027

Those are not integers, those are strings. They happen to be strings containing characters also used to represent integers in other contexts, but they are strings nonetheless and so this is valid JSON. From the JSON spec:

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.

Something like this would not be valid JSON:

{ 1:"32.1093904, 66.7065216", 
  2:"33.1236854, 67.8128443", 
}

...because here the characters are not wrapped in double quotes, and so not valid keys in JSON.

Upvotes: 2

Related Questions