Access and modify a JSON file in a specific directory

Hey All, 

I would like to know is there any API to read a JSON file in a specific directory programmatically inside the plugin, and after that make some changes to the file and store it in the path that I read the JSON file from it. 

Thank you in advance. 



There are two ways of doing that.

1) Using IntelliJ APIs: com.intellij.openapi.vfs.VirtualFileManager#findFileByUrl, com.intellij.openapi.fileEditor.FileDocumentManager#getDocument, com.intellij.psi.PsiDocumentManager#getPsiFile.

You're welcome to read more about that in our docs.

Once you get your PsiFile, you have the PSI: AST coupled with semantic entities like references. You may modify the PSI the way you need (if you need to create new elements, use com.intellij.json.psi.JsonElementGenerator), and then you commit the document, and voila.

We also provide some documentation on working with the PSI.

2) Using some third-party library like Gson. Actually this may come easier if you need to perform only very basic tree manipulations in one single file, and if you don't need to have any extra smartness like searching for usages, renaming or working with schemas.

Feel free to ask any further questions.


Thanks Anton for your help, 

Actually, I just need to change some values of this JSON file, i.e, if the original JSON file has an property like "user":"", I would like to change it to "user":"Amir". so, if I want to follow the first option, for the aforementioned purpose can I used ""?

or you suggest to go for a third-party library? 




Use com.intellij.json.psi.JsonElementGenerator#createValue to create a new string value, and com.intellij.psi.PsiElement#replace to replace the original value.

To traverse your PSI file, you may:

- use com.intellij.psi.SyntaxTraverser#psiTraverser()

- traverse it manually: com.intellij.json.psi.JsonFile#getTopLevelValue, then check if it is a JsonObject, then enumerate object properties, each property has just another JsonValue as its value, and so on

(I'm going to introduce a JSON Pointer public API for version 2018.3, so that it would be possible to quickly get a nested element by using a JSON Pointer - much easier than traversing the PSI manually. But that API is not there yet, and if using it, your plugin will be compatible only with 2018.3 and higher.)


You may use the PSI Viewer tool window to make you feel more comfortable with what the PSI is and how it is structured.


Please sign in to leave a comment.