[PYTHON] Handle JSON files with Matlab

Simple note

It seems that it is possible to handle JSON format from MATLAB 2016b. jsondecode jsonencode

Prepare the following files and check how to use them.

test.json


[
  {
    "Null": null,
    "Boolean": true,
    "Numeric": 1,
    "String": "string",
    "Object": { "a": null, "b": true, "c": 1, "d": "string" },
    "Array": [ null, true, 1, "string" ],
    "BooleanArray": [ true, false],
    "NumericArray": [ 1, 2, 3 ],
    "StringArray": [ "foo", "buz" ],
    "ObjectArrayS": [ { "a": 1, "b": "one" }, { "a": 2, "b": "two" } ],
    "ObjectArrayC": [ { "a": 1, "b": "one" }, { "x": 9, "y": true } ]
  }
]

procedure

: one: Read JSON file Use ** jsondecode **

>> json = jsondecode(fileread('test.json'))

json = 

Struct with field:

            Null: []
         Boolean: 1
         Numeric: 1
          String: 'string'
          Object: [1×1 struct]
           Array: {4×1 cell}
    BooleanArray: [2×1 logical]
    NumericArray: [3×1 double]
     StringArray: {2×1 cell}
    ObjectArrayS: [2×1 struct]
    ObjectArrayC: {2×1 cell}

: two: Encode structured MATLAB data as JSON-formatted text Use ** jsonencode **. The output of this function is a string representing a one-line JSON object. It should be noted here that jsonencode cannot output null.

JSON MATLAB MATLAB JSON
null :arrow_right: [] [] :arrow_right: []
>> jsonencode(json)

ans =

    '{"Null":[],"Boolean":true,"Numeric":1,"String":"string","Object":{"a":[],"b":true,"c":1,"d":"string"},"Array":[[],true,1,"string"],"BooleanArray":[true,false],"NumericArray":[1,2,3],"StringArray":["foo","buz"],"ObjectArrayS":[{"a":1,"b":"one"},{"a":2,"b":"two"}],"ObjectArrayC":[{"a":1,"b":"one"},{"x":9,"y":true}]}'

Use low-level file I / O to write text files.

>> fileID = fopen('test2.json', 'w');
>> fprintf(fileID, jsonencode(json));
>> fclose(fileID);

Unfortunately, the current version of matlab doesn't support JSON formatting. Therefore, use python's json.tool to format the JSON file output by matlab. It's a bit sloppy, but if you have an environment where you can run python on the command line, you can run python on the matlab console as well. https://jp.mathworks.com/help/matlab/matlab_external/run-external-commands-scripts-and-programs.html

>> !python -m json.tool test2.json test3.json

test3.json


{
    "Null": [],
    "Boolean": true,
    "Numeric": 1,
    "String": "string",
    "Object": {
        "a": [],
        "b": true,
        "c": 1,
        "d": "string"
    },
    "Array": [
        [],
        true,
        1,
        "string"
    ],
    "BooleanArray": [
        true,
        false
    ],
    "NumericArray": [
        1,
        2,
        3
    ],
    "StringArray": [
        "foo",
        "buz"
    ],
    "ObjectArrayS": [
        {
            "a": 1,
            "b": "one"
        },
        {
            "a": 2,
            "b": "two"
        }
    ],
    "ObjectArrayC": [
        {
            "a": 1,
            "b": "one"
        },
        {
            "x": 9,
            "y": true
        }
    ]
}

The position of the line break is slightly different, but it can be reproduced except for ** null **. The difficulty is that an intermediate file (test2.json) is generated.

Other

The data that can be represented by MATLAB and JSON are not completely compatible. Refer to the following when expressing data so as to maintain compatibility with MATLAB variables. https://jp.mathworks.com/help/mps/restfuljson/json-representation-of-matlab-data-types.html However, reading for this format does not seem to be implemented.

Recommended Posts

Handle JSON files with Matlab
Handle csv files with Django (django-import-export)
Handle Excel CSV files with Python
Reading and writing JSON files with Python
Handle zip files with Japanese filenames in Python 3
Upload files with Django
[Python] Use JSON with Python
json parse with gdb
Handle Excel with python
Handle rabbimq with python
[Day 6] Handle static files
Load nested json with pandas
How to handle static files when deploying to production with Django
POST json with Python3 script
Sorting image files with Python (2)
Sort huge files with python
Sorting image files with Python (3)
[Tips] Handle Athena with Python
Transfer files with teraterm [Note]
Reading .txt files with Python
Handle numpy arrays with f2py
Format json with Vim (with python)
Read json data with python
Handle Base91 keys with python + redis.
Let's upload S3 files with CLI
Recursively unzip zip files with python
Manipulating EAGLE .brd files with Python
Enumerate files with a specific extension
Easily handle lists with python + sqlite3
Load multiple JavaScript files with PyWebView
Manage Django config files with Python-decouple
[Python] POST wav files with requests [POST]
Serve static files with X-Send File
Decrypt files encrypted with OpenSSL with Python 3
Upload & move GCS files with Go
JSON encoding and decoding with python
Install the data files with setup.py
Save and retrieve files with Pepper
Easily handle databases with Python (SQLite3)
Read files in parallel with Python
Merge JSON format data with Ansible
Handle various date formats with pandas