0

My backend is built with express (so basically javascript). The backend is also able to save some data to .json files and use this data.

var data = JSON.parse(fs.readFileSync("path/data.json"));

It would help me a lot, if Visual Studio Code would provide Intellisense for my data object (like suggesting all elements of this json file). Is there any addon for this kind of "problem" ?

Example:

{
    "owner": "testperson",
    "age": "30"
}

After parsing this json file (exact way like on top), it would be very helpful to have Intellisense after writing

data. 
Henry
  • 87
  • 7
  • What does "suggesting all elements of this json file" mean? – Andy Mar 13 '22 at 11:07
  • I have updated my question with an example. – Henry Mar 13 '22 at 11:12
  • @Marco You could use JSDoc comments to define a special type for the data variable and mark the variable with that type. This is the link to the documentation for the functionality you need: https://jsdoc.app/tags-typedef.html VS Code does understand JSDoc comments out of the box. – Palladium02 Mar 13 '22 at 11:22
  • Does this answer your question? [is there a require for json in node.js](https://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js) – tevemadar Mar 13 '22 at 12:05
  • @tevemadar You can use require to load a JSON file but the question was how to get intellisense for the content, which is not the case when using require. – Palladium02 Mar 13 '22 at 12:09

1 Answers1

1

There is a built-in solution in VSCode exactly that manner. To get intellisense VSCode needs to know what the type of something is and for that you can use JSDoc comments, if you want to stick to JavaScript. These are understood by VSCode without any problem. The snippet down below is applies to your given example.

/**
  * @typedef {Object} MyData
  * @property {string} owner
  * @property {number} age
*/

/**
  * @type {MyData}
*/
let data = JSON.parse(fs.readFileSync("path/data.json"));

For further reading I refer to the JSDoc docs.

Palladium02
  • 1,134
  • 1
  • 4
  • 13