3

I'm using the JSON-FRAMEWORK in objective C to parse a JSON object. When I call [jsonString JSONValue], I get back a dictionary, but the keys aren't in the same order as the JSON Object I'm parsing. Is there anyway to keep this order the same?

5
  • Why would you need to keep the order the same? It's a dictionary--accessing an element by key is an O(1) operation. Commented Aug 25, 2011 at 23:40
  • Because I have a separate object that has an index attribute. This index is supposed to correspond to the order in which keys are in in the json object. Since it appears to be the case that the dictionary's keys will be unordered, I guess I'll have to figure out a different way to make the connection between my object, and the key it should correspond to in the dictionary Commented Aug 25, 2011 at 23:48
  • Instead of an index you could simply store the dictionary key ... Commented Aug 25, 2011 at 23:54
  • Right. Or I might just pass in the index into the json object. Commented Aug 25, 2011 at 23:59
  • 3
    Um, the whole point is that "index into the JSON object" is meaningless since JSON objects are unordered. Commented Aug 26, 2011 at 0:35

1 Answer 1

17

In JSON objects, by definition, the order of the key-value pairs is not meaningful. The specification allows a JSON producer to permute them any way it want, even at random -- and does not require a parser to preserve the ordering. RFC 4627 says:

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

If you need the ordering to be preserved, what you have is not JSON, but a home-defined format that just happens to look superficially like JSON.

Sign up to request clarification or add additional context in comments.

1 Comment

maybe "happens to look superficially like" is a little harsh. It would act mostly like JSON, but would have a non-trivial difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.