Eduardo Pignatelli
Eduardo Pignatelli

Reputation: 183

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.

Upvotes: 3

Views: 9672

Answers (2)

Chuck
Chuck

Reputation: 2102

I also want to read a JSON file with Octave, which is how I found this question. I also found this answer, stating that there's a Matlab built-in method called jsondecode, so I went looking for that function and discovered that the same functionality now exists in Octave.

jsondecode will decode a JSON string, and jsonencode will convert a struct to a JSON string.

Here's a link to the documentation, and here's a link to the package, which appears to have been released in August, 2021.

If you want to read a JSON file from disk, simply run

json_data = jsondecode(fileread('/path/to/your.json'));

Upvotes: 0

Andy
Andy

Reputation: 8091

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
        ]
    ]
}

Upvotes: 4

Related Questions