Jump to content

Help with adding to JSON file


Go to solution Solved by AspirinJunkie,

Recommended Posts

Posted (edited)

I am honestly embarrassed to be stuck on what seems like simple manipulation of a simple text-based file. I have modified json files manually for years. But I am trying to modify json programmatically in a current project.

I have spent two weeks playing around with four different json UDFs and I still cannot figure out how to simply add a few lines to a json file. I am close to losing my mind with my current project.

Needless to say, I am desperate for help on this issue. If you have a better understanding of json and have a moment, I would appreciate it greatly.

I am trying to modify the VSCode/VSCodium settings.json file from within AutoIt.

Here is a basic example:

{
    "workbench.startupEditor": "none",
    "breadcrumbs.enabled": false,
    "window.controlsStyle": "custom",
    "workbench.activityBar.location": "hidden"
}

So for example, I would like to add the following:

"workbench.colorCustomizations": {
     "editor.background": "#00000060",
     "terminal.background": "#00000000"
     },
"window.customTitleBarVisibility": "auto",
"window.titleBarStyle": "custom",
"window.controlsStyle": "custom",

As far as I understand, the workbench.colorCustomizations is the only option that has nested items. Or at least, the only nested one that I am interested in.

Now, it is also possible that I could have a starting point looking like this:

{
    "workbench.colorCustomizations": {
          "editor.background": "#00000060"
        },
    "workbench.startupEditor": "none",
    "breadcrumbs.enabled": false,
    "window.controlsStyle": "custom",
    "workbench.activityBar.location": "hidden"
}

In this case, I would need to add "terminal.background": "#00000000" to workbench.colorCustomizations and the other 3 settings to the bottom of the main part.

What I am trying to do seems simple. Yet I've spent weeks of time and failed at every attempt. I am sure that somebody with combined AutoIt experience and JSON experience can do this while blindfolded.

Sorry for asking something that seems so basic. But I really would be thankful for any help. Thank you.

Edited by WildByDesign
removed part about filewriteline and fileexists
  • Solution
Posted
44 minutes ago, WildByDesign said:

I have spent two weeks playing around with four different json UDFs

If by chance my UDF was included - I would implement it like this:

#include "JSON.au3"

; your input JSON string
Global $sJSONRAW = '{"workbench.startupEditor": "none","breadcrumbs.enabled": false,"window.controlsStyle": "custom","workbench.activityBar.location": "hidden"}'

; parse JSON string into nested AutoIt data structure:
Global $vJSON = _JSON_Parse($sJSONRAW)
If @error Then Exit MsgBox(0,"Erro", "Error " & @error &  " during parsing the JSON string")

; print to console to check the structure of the input JSON string
ConsoleWrite("------- Input --------- " & @CRLF & _JSON_Generate($vJSON) & @CRLF & @CRLF)

; add (or change if they already exists) the desired values
; for these values you can directly use the outer map because $vJSON is the outer map
$vJSON["window.customTitleBarVisibility"] = "auto"
$vJSON["window.titleBarStyle"]            = "custom"
; for inner nested elements you can use _JSON_addChangeDelete() instead (points must be escaped)
_JSON_addChangeDelete($vJSON, "workbench\.colorCustomizations.editor\.background", "#00000060")
_JSON_addChangeDelete($vJSON, "workbench\.colorCustomizations.terminal\.background", "#00000060")

; create JSON string out of the AutoIt datastructure and print it to the console
ConsoleWrite("------- Output --------- " & @CRLF & _JSON_Generate($vJSON) & @CRLF & @CRLF)

 

Posted
31 minutes ago, AspirinJunkie said:

If by chance my UDF was included - I would implement it like this:

Thank you so much. Yes, I did spend a good amount of time with your UDF as well.

Your UDF is fantastic, by the way. So the problem was not to do with your UDF. The problem was my complete lack of understanding for the JSON format and lack of proper terminology for JSON on my part. I played around with the examples provided, but the examples were structured differently in comparison to the VSCode settings.json file and I simply got lost in my own lack of understanding JSON structure.

Question: With your example above, as I understand it _JSON_Generate($vJSON) will generate the final JSON to output. How do I take that final JSON output and write it back to the settings.json file?

I want to ensure that whatever method is used to write back to the JSON file on disk that I don't change the UTF-8 encoding type or the language mode (JSON with Comments) that seem to be default with the settings.json file for VSCode.

Posted
7 minutes ago, WildByDesign said:

Question: With your example above, as I understand it _JSON_Generate($vJSON) will generate the final JSON to output. How do I take that final JSON output and write it back to the settings.json file?

All you have to do is write the generated string to a file and tell the output function to use UTF-8 as the encoding.
You can specify the encoding manually with FileOpen(), but if you address FileWrite() directly with a file name, it will automatically write the passed string to the file encoded as UTF-8 (To overwrite, delete the file before FileWrite with FileDelete).

18 minutes ago, WildByDesign said:

I want to ensure that whatever method is used to write back to the JSON file on disk that I don't change [...} the language mode (JSON with Comments) that seem to be default with the settings.json file for VSCode.

The UDF cannot handle comments in JSON because they are not standard-compliant.
You already get an error when parsing with _JSON_Parse().

Therefore, there are also no comments that can be adopted in any way, so that handling these files and the UDF is therefore not intended.

 

Perhaps a few words for basic understanding:
JSON only describes how data and its hierarchy can be represented as a string.

It is therefore well suited as an exchange format between different systems, as the basic data types and structures used in JSON are found in the vast majority of programming languages. It is also easy to read by humans.

When working with JSON, however, this means that you only have to deal with it twice: once to convert a JSON string into the data structure of your program (_JSON_Parse) and a second time to generate a JSON string from the data structures of your program (_JSON_Generate). Everything in between (changing/adding/deleting data etc.) basically has nothing to do with JSON but simply data manipulation within the data structures in your respective program.

Posted (edited)

I know you solved it, just for a deeper understanding, on how   (I'm a rookie too) :)

; with string manipulation, 
; the convenient point is the intermediate '},'
; which you can add before it for terminal.background
; or after it for window.customTitleBarVisibility, window.titleBarStyle
    
    
Local $sTxt = '{"workbench.colorCustomizations": {"editor.background": "#00000060"}, "workbench.startupEditor": "none", "breadcrumbs.enabled": false, "window.controlsStyle": "custom", "workbench.activityBar.location": "hidden"}'
ConsoleWrite($sTxt & @CRLF)

Local $sNewEntry, $sNewTxt

; add terminal.background to workbench.colorCustomizations
$sNewEntry = ', "terminal.background": "#00000000"'
$sNewTxt = StringReplace($sTxt, '},', $sNewEntry & '},') ; * and the replace part

; add the other 2 settings ,I don't understand who the third one is, but it shouldn't have the same name.
$sNewEntry = ' "window.customTitleBarVisibility": "auto","window.titleBarStyle": "custom",'
$sNewTxt = StringReplace($sNewTxt, '},', '},' & $sNewEntry) ; * and the replace part

ConsoleWrite($sNewTxt & @CRLF)

 

Edited by ioa747

I know that I know nothing

Posted
20 minutes ago, AspirinJunkie said:

You can specify the encoding manually with FileOpen(), but if you address FileWrite() directly with a file name, it will automatically write the passed string to the file encoded as UTF-8 (To overwrite, delete the file before FileWrite with FileDelete).

Thank you for this suggestion. I ended up going with the FileOpen / FileWrite method and all of the data saved exactly as I was hoping. 

By the way, your UDF is so fantastic and does the job smoothly. For example, the fact that it will add the options (if they don't exist) or modify the options if they do already exist is such beautiful functionality. Excellent! :)

23 minutes ago, AspirinJunkie said:

The UDF cannot handle comments in JSON because they are not standard-compliant.
You already get an error when parsing with _JSON_Parse().

It looks like the VSCode settings.json doesn't actually use json comments. I assume that this is just the default automatically selected language mode in VSCode when you open a json file.

29 minutes ago, AspirinJunkie said:

Perhaps a few words for basic understanding:
JSON only describes how data and its hierarchy can be represented as a string.

It is therefore well suited as an exchange format between different systems, as the basic data types and structures used in JSON are found in the vast majority of programming languages. It is also easy to read by humans.

When working with JSON, however, this means that you only have to deal with it twice: once to convert a JSON string into the data structure of your program (_JSON_Parse) and a second time to generate a JSON string from the data structures of your program (_JSON_Generate). Everything in between (changing/adding/deleting data etc.) basically has nothing to do with JSON but simply data manipulation within the data structures in your respective program.

This was very helpful and beneficial. I really appreciate your time. Cheers! :)

Posted
7 minutes ago, ioa747 said:

I know you solved it, just for a deeper understanding, on how   (I'm a rookie too) :)

Thank you. This is a really neat technique as well. I learned some more from your technique as well that will benefit me.

By the way, the third setting that you did not know what it is ("window.controlsStyle": "custom") is a more recent setting in latest versions of VSCode that allow custom window control buttons. In my case, it allows making them transparent and accepting of the Windows 11 backdrop materials like Mica, Acrylic, etc.

Posted
9 minutes ago, WildByDesign said:

By the way, the third setting that you did not know what it is ("window.controlsStyle": "custom")

the issue is that it already exists in the starting point , and when I put it in it again,  gave me an invalid json
That's why I left it outside.

(for validation I use notepad++, with a 'JSON Tools' plugin that has)

I know that I know nothing

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...