7

According to the following post;

Does JSON syntax allow duplicate keys in an object?

Keys with the same name in JSON are valid, but most parsers will override the value with the last value it finds. Is there anyway in a json schema to detect duplicate names and throw an error? I want all json keys to have unique names in an object.

Community
  • 1
  • 1
Mike Mellor
  • 1,316
  • 17
  • 22
  • It would require a custom parser which is duplicate-aware to parse the schema itself. I don't think it exists yet. – This company is turning evil. Oct 08 '14 at 14:52
  • Ahh thats a shame, i figured this must have been an issue for other people, is there really no solution already out there? – Mike Mellor Oct 08 '14 at 15:02
  • A relatively fast search on Google gave no results. I guess your best bet would write your own JSON parser which accounts for such duplicate keys. Interstellarly far from a optimal solution, but better than nothing. You could also preprocess your JSON to something non-duplicated. – This company is turning evil. Oct 08 '14 at 23:35
  • Ye i tried searching for a while with no luck, ok no problem, ye i'm already in a pre-process work flow so adding some task to remove duplicate objects from json should be relatively easy. Thanks for your help – Mike Mellor Oct 09 '14 at 08:13

2 Answers2

6

Json-schema works with valid JSON objects, so there is nothing it can do to prevent duplicate keys.

I would suggest you to use a jsonlint as a preprocess before validating with json-schema validator. It will depend on your programming language but here you have some choices:

jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
1

If you're looking for a method to detect the duplicate keys in C#, then just use JObject.Parse method with specific parameter in Json.NET.

try
{
    var _= JObject.Parse(jsonString, new JsonLoadSettings
    {
        DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error
    });
}
catch(JsonReaderException ex)
{
    return BadRequest($"Invalid json file, {ex.Message}.");
}
Johnny Qian
  • 668
  • 7
  • 14