Loading JSON File

I am trying to use the JSON XOP - my first time trying to use an XOP - but having problems with the instructions. The instructions are clear after loading the JSON file into a string.

Question: How do I load the JSON file to a JSON string to then use JSONXOP_GetValue to pass the data into waves?

Thank you!

Best,

Loading an arbitrary file is not exactly straightforward. Something like the following should do the trick:

 

#include "json_functions"

Function JsonLoadFromFile(string path)

    variable refNum
    string contents

    Open/R/Z refNum as path
    if(V_Flag)
        return NaN
    endif

    FStatus refNum
    contents = PadString("", V_LogEOF, 0)
    FBinRead refNum, contents
    Close refNum

    return JSON_Parse(contents, ignoreErr = 1)
End

This returns  NaN on error or a valid jsonID in the sucess case.

JSON_Parse appears to be available on IGOR 8. I am still on 6. Perhaps is time to upgrade!

Hi 

I have a large json file (see attachment). I want to have the values put in igor waves. How can I use the function above in order to do that? Where do I load the file? How can I get this to run?

 

Cheers

Silvan

json file as txt

@Silvan:

You need the JSON-XOP from https://docs.byte-physics.de/json-xop/. Install it.

And then you can use the below code as a starting point:

#include "json_functions"

Function/WAVE JsonLinesLoadFromFile(string path)

    variable refNum
    string contents

    Open/R/Z refNum as path
    if(V_Flag)
        return $""
    endif

    FStatus refNum
    contents = PadString("", V_LogEOF, 0)
    FBinRead refNum, contents
    Close refNum
   
    WAVE/T wv = ListToTextWave(contents, "\n")
    return wv
End

Function ExtractFromLine(string JSONText)
    variable jsonID, temp

    // fixup non-conformant JSON with NaNs as numbers to NaNs as strings
    JSONText = ReplaceString(": NaN,",JSONText, ": \"NaN\", ")

    jsonID = JSON_Parse(JSONText, ignoreErr = 1)
    if(numtype(jsonID) != 0)
        return NaN
    endif

    temp = JSON_GetVariable(jsonID, "cpu_temperature")

    JSON_Release(jsonID)
   
    return temp
End

Function Parse()

    WAVE/T contents = JsonLinesLoadFromFile("E:\\walk_A2.txt")

    Make/N=(DimSize(contents, 0))/O cpuTemp = ExtractFromLine(contents[p])
End

This is not a pure JSON file, it is in JSONLines format, https://jsonlines.org/, where each line is its own JSON document.

Whoever produced that file did also not create a standards-compliant file, as you can not use NaN when a number is expected. I've added some hacky fix for that.