1

Working on JSON file in VS Code that is feeding big app with multiple layers that all have "ID" tag that needs to be unique or the app is broken. Multiple people are working on it and with large number of layers it is hard to keep track. Is there a way to make it appear as error or a warning to a user if there are 2 identical IDs or to make some script that will check it.

Sample code:

"layers":[
{ 
"id": "firstID",
"name": "name1"
},
{
"id": "secondID",
"name": "name2"
},
{
"id": "thirdID",
"name": "name3"
},
{
"id": "firstID",
"name": "name4"
}]

As seen in this code, is it possible for VS code to mark or make and error for last object as it have same "id" as first?

Thanks in advance

Jacopo Tedeschi
  • 149
  • 1
  • 8
Ivan
  • 11
  • 1
  • While direct editing of JSON files should be avoided as much as possible, there are situations when fast feedback is needed and a small manual edit is the best choice. My suggestion would be to create a small script in node.js and use the `chokidar-cli` package to sense for changes and run it. Probably using VS Code Workspace automation you may be able to automate script execution, and make it run as soon as the workspace is opened. Example of usage of chokidar-cli: `chokidar "./your-file.json" -c "npm run check-json-id"` – Jacopo Tedeschi Feb 01 '22 at 12:18
  • One feature in VS Code you may want to look into is the [native custom JSON Schema support](https://code.visualstudio.com/docs/languages/json#_json-schemas-and-settings). It seems hard to make it work for your needs, but once you set it up it provides suggestions and highlights in JSON files. It can be used to ["require" certain keys](https://json-schema.org/understanding-json-schema/reference/object.html#required-properties) in objects, though the standard currently does not support checking unique values. – Jacopo Tedeschi Feb 01 '22 at 14:55
  • It is possible to add support for unique values outside of the standard using a tool like [Ajv validator](https://github.com/ajv-validator/ajv/tree/v6), and adding the custom JSON-Schema keyword uniqueItemProperties using [ajv-validator/ajv-keywords](https://github.com/ajv-validator/ajv-keywords#uniqueitemproperties), though I never tried using it, and cannot guarantee how good it is. Instead, if it is possibile for you to change your JSON array into an object you may also try to look into [this answer](https://stackoverflow.com/a/36771213/15084902). – Jacopo Tedeschi Feb 01 '22 at 15:04

0 Answers0