Writing JSON schema to detect objects with duplicate names
Asked Answered
B

3

8

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.

Banker answered 8/10, 2014 at 14:48 Comment(4)
It would require a custom parser which is duplicate-aware to parse the schema itself. I don't think it exists yet.Mcilwain
Ahh thats a shame, i figured this must have been an issue for other people, is there really no solution already out there?Banker
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.Mcilwain
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 helpBanker
T
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:

Trophoplasm answered 9/10, 2014 at 11:20 Comment(0)
S
2

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}.");
}
Swayback answered 1/8, 2023 at 7:19 Comment(0)
I
0

As the accepted answer states, JSON Schema just cannot enforce the check you want to implement (the equivalent of minOccurs="1" maxOccurs="1" in XML).

I just would like to add that the link to the Python validator is broken. Python programmers might install demjson3 and run jsonlint my-json-file.json; duplicate elements will trigger a warning (Warning: Object contains duplicate key)

Iorgo answered 3/10, 2023 at 15:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.