jsonoctave

How to parse json file in Octave?


As in the title, is there a built-in way of parsing/decoding a .json file in Octave?

I have gone through the Octave documentation, and different tools, but the only thing I have found is this tool: https://github.com/fangq/jsonlab

EDIT: The purpose is to be able to use the same json config file for two different environments: python and octave. So the would be: 1. Define the config; 2. Run octave script, reading the config from config.json; 3. Run python script, reading the config from config.json;

I am using at the moment the jsonlab toolset for octave, and since the json is fairly simple, it is working really good. Question is coming from pure curiosity of why octave does not implement a json serialization library by default.

So, since the json is simple, solution for me is to use https://github.com/fangq/jsonlab. From the comments below, seems that that is not perfect to be used with more complex jsons.


Solution

  • I've used JSONlab for many projects for a long time but because it was very slow and some points didn't fulfilled my expectation I wrote a octave wrapper around rapidjson: https://github.com/Andy1978/octave-rapidjson

    README.md shows some examples. One example to get a reply from a server as JSON, then convert it to a struct:

    octave:1> x = load_json (urlread ("http://headers.jsontest.com/"))
    x =
    
      scalar structure containing the fields:
    
        X-Cloud-Trace-Context = 61910c1954c45fe021d35aeeb5477c20/2702800337619378204
        Host = headers.jsontest.com
        Accept = */*
    
    octave:2> x.Host
    ans = headers.jsontest.com
    

    The other way:

    octave:11> a.x = 5; a.y = {1,2,"foobar"}; a.z = rand(2); save_json (a)
    ans = {
        "x": 5.0,
        "y": [
            1.0,
            2.0,
            "foobar"
        ],
        "z": [
            [
                0.6835708677160701,
                0.891779233104656
            ],
            [
                0.9378550691771155,
                0.664043049215685
            ]
        ]
    }