zanders3/json

Technically valid JSON not parsed

Closed this issue · 3 comments

Nothing in the JSON spec says you can't have duplicate keys. So e.g. I have come across JSON like this which made it through other JSON processors in the wild:

{
   "name": "Peter",
   "age": 31,
   "name": "Peter"
}

When using TinyJson.JSONParser.FromJson<Dictionary<string, object>> on the document above, it throws an error saying that the dictionary already contains a key of the same name.

This behaviour might be desirable in some circumstances, but I need to use it in a way which ensures it can cope with strange files like the one above. In the case shown, most processors just overwrite the first value of name with the subsequent one(s).

I'd say the code should default to allowing valid JSON and allow turning on of this "duplicate key handling by exception" behaviour via some sort of flag?

In our case we've changed:

241    object val = ParseValue(valueType, elems[i + 1]);
242    dictionary.Add(keyValue, val);
243 }

to:

241    object val = ParseValue(valueType, elems[i + 1]);
242    dictionary[keyValue] = val;
243 }

and

268 for (int i = 0; i < elems.Count; i += 2)
269    dict.Add(elems[i].Substring(1, elems[i].Length - 2), ParseAnonymousValue(elems[i + 1]));
270 return dict;

to:

268 for (int i = 0; i < elems.Count; i += 2)
269   dict[elems[i].Substring(1, elems[i].Length - 2)] = ParseAnonymousValue(elems[i + 1]);
270 return dict;

I think this is just an oversight on my part. The library is not meant to throw exceptions - so I agree that silently overwriting duplicate keys is the better option here.
Could you make a pull request with the above changes?

pending. I wasn't sure of white-space conventions as it's currently inconsistent within the files.

Once this PR is in, happy to follow up with white-space formatting.