1

I have uploaded a *.mat file that contains a 'struct' to my jupyter lab using:

from pymatreader import read_mat
data = read_mat(mat_file)

Now I have a multi-dimensional dictionary, for example:

data['Forces']['Ss1']['flap'].keys()

Gives the output:

dict_keys(['lf', 'rf', 'lh', 'rh'])

I want to convert this into a JSON file, exactly by the keys that already exist, without manually do so because I want to perform it to many *.mat files with various key numbers.

EDIT: Unfortunately, I no longer have access to MATLAB. An example for desired output would look something like this:

json_format = {
"Forces": {
  "Ss1": {
    "flap": {
      "lf": [1,2,3,4],
      "rf": [4,5,6,7],
      "lh": [23 ,5,6,654,4],
      "rh": [4 ,34 ,35, 56, 66]
        }
      }
    }
  }

ANOTHER EDIT: So after making lists of the subkeys (I won't elaborate on it), I did this:

FORCES = []
for ind in individuals:
  for force in forces:
    for wing in wings:
      FORCES.append({
          ind: {
              force: {
                  wing: data['Forces'][ind][force][wing].tolist()
 
              }
          }
      })

Then, to save:

with open(f'{ROOT_PATH}/Forces.json', 'w') as f:
    json.dump(FORCES, f)

That worked but only because I looked manually for all of the keys... Also, for some reason, I have squared brackets at the beginning and at the end of this json file.

2 Answers2

3

The json package will output dictionaries to JSON:

import json

with open('filename.json', 'w') as f:
    json.dump(data, f)
DMR
  • 1,479
  • 1
  • 8
  • 11
  • I get an TypeError: Object of type bytes is not JSON serializable – Ziv Kassner Feb 28 '21 at 18:44
  • Now TypeError: Object of type ndarray is not JSON serializable... I'm starting to think it is undoable – Ziv Kassner Feb 28 '21 at 19:49
  • These errors are because in addition to numeric values, you also have byte or Numpy arrays that have to be converted before being serialized to JSON. See for example: https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable – DMR Feb 28 '21 at 19:54
0

If you are using MATLAB-R2016b or later, and want to go straight from MATLAB to JSON check out JSONENCODE and JSONDECODE. For your purposes JSONENCODE

encodes data and returns a character vector in JSON format. MathWorks Docs

Here is a quick example that assumes your data is in the MATLAB variable test_data and writes it to a file specified in the variable json_file

json_data = jsonencode(test_data);
writematrix(json_data,json_file);

Note: Some MATLAB data formats cannot be translate into JSON data due to limitations in the JSON specification. However, it sounds like your data fits well with the JSON specification.

Azim J
  • 8,260
  • 7
  • 38
  • 61