Search code examples
nsisnsjsonserializationelectron-packager

Read And Update JSON File Using nsJSON Plugin (NSIS)


I am trying to update one data on JSON file using nsJson Plugin.

My JSON data on File

{   "header_left_lebel": "LEFT LEBEL",
    "header_center_label": "CENTER LEBEL",
    "base_path": "E:\Workspace\my-demo-app"
}

I want to edit the base path during installation of the application.

My Code to Read and Update the Value

Section "Installation Section"
    SetOutPath "$INSTDIR" 

    GetFullPathName $0 ..
    StrCpy $installationPath "$0\${applicationName}";This Holds the installation path

    nsJSON::Set /file `$installationPath/config/settings.json`
    nsJSON::Set `base_path` /value `"$installationPath"`
    nsJSON::Serialize /file `$installationPath/config/settings.json`

   WriteUninstaller "$INSTDIR\Uninstall.exe"
SectionEnd

The above code updates the JSON file but it only keeps base_path

I want to keep all the data and only to update base_path

Any help or links will be appreciated.


Solution

  • Your code works correctly for me when using NSIS v3.04 and JSON plug-in v1.1.1.0 (November 2017):

    Unicode True
    
    !macro DumpTxtFile file
    Push "${file}"
    Call DumpTxtFile 
    !macroend
    Function DumpTxtFile 
    Exch $0
    Push $1
    FileOpen $0 $0 r
    loop:
        ClearErrors
        FileRead $0 $1
        IfErrors done
        DetailPrint $1
        Goto loop
    done:
    FileClose $0
    Pop $1
    Pop $0
    FunctionEnd
    
    !include LogicLib.nsh
    Section
    FileOpen $0 "$temp\NSIStest.json" w
    FileWrite $0 '{   "header_left_lebel": "LEFT LEBEL",$\r$\n'
    FileWrite $0 '    "header_center_label": "CENTER LEBEL",$\r$\n'
    FileWrite $0 '    "base_path": "E:\Workspace\my-demo-app"$\r$\n'
    FileWrite $0 '}'
    FileClose $0
    !insertmacro DumpTxtFile "$temp\NSIStest.json"
    
    Var /Global installationPath
    StrCpy $installationPath "c:\dummy\path"
    
    ClearErrors
    nsJSON::Set /file `$temp\NSIStest.json`
    nsJSON::Set `base_path` /value `"$installationPath"`
    nsJSON::Serialize /format /file `$temp\NSIStest.json`
    ${If} ${Errors}
      Abort "Unable to update JSON file!"
    ${EndIf}
    
    !insertmacro DumpTxtFile "$temp\NSIStest.json"
    SectionEnd