Search code examples
jsonnsis

Using NSIS, How can I get the Key Value from a text file in Json format or a Json file?


I'm jin. Thanks for reading my article :)

I am using NSIS, and I want to get the key value inside by using C++ dll to get a Json type string and save it as a text file or Json file. But even using nsJson I don't get the value. We will send you a simple example and code. thank you.

file Example : "ex.json" or "ex.txt"

[{"areaCode":"INF0411","areaName":"NewY","gradeCode":"INF0102"},
{"areaCode":"INF0412","areaName":"NewA","gradeCode":"INF0103"},
{"areaCode":"INF0413","areaName":"NewB","gradeCode":"INF0104"},
{"areaCode":"INF0414","areaName":"NewC","gradeCode":"INF0105"}]

In this situation, I want to get the key value of every "gradeCode".

Thanks for reading.


Solution

  • Use /index to access array nodes:

    !macro prepare_example
    InitPluginsDir
    FileOpen $0 "$PluginsDir\data.json" w
    FileWrite $0 '[{"areaCode":"INF0411","areaName":"NewY","gradeCode":"INF0102"},$\n'
    FileWrite $0 '{"areaCode":"INF0412","areaName":"NewA","gradeCode":"INF0103"},$\n'
    FileWrite $0 '{"areaCode":"INF0413","areaName":"NewB","gradeCode":"INF0104"},$\n'
    FileWrite $0 '{"areaCode":"INF0414","areaName":"NewC","gradeCode":"INF0105"}]$\n'
    FileClose $0
    !macroend
    
    !include LogicLib.nsh
    Section
    !insertmacro prepare_example
    
    ClearErrors
    nsJSON::Set /file "$PluginsDir\data.json"
    nsJSON::Get /count /end
    Pop $1
    ${For} $2 0 $1
        nsJSON::Get /index $2 "gradeCode" /end
        ${IfNot} ${Errors}
            Pop $0
            DetailPrint "Grade=$0"
        ${EndIf}
        ${Next}
    
    SectionEnd