2
{
  "NX-Matlab":
 {
    "Volumen": 200,
    "Wanddicke": 3
  },

  "Matlab-NX": {

    "n1": {
      "Fließ barriere oder Fließhilfe": 1,
      " Querschnittsart": 1,
      "Geometrieparameter": {
        "Breite": 2,
        "Höhe": 4.479,
        "Anzahl": 3

Code:

clc


fid = fopen('filename.json', 'r');

str = fread(fid,'*char').';

fclose(fid);

J = jsondecode(str);

J.Matlab_NX.n1.Geometrieparameter.Breite = 3;

outputjson = jsonencode(J);

fileID = fopen('filename.json','w');
fwrite(fileID, outputjson);
fclose(fileID);

I wanted to replace Updated parameter (Breite) in file. Need guidance.

0

3 Answers 3

4

If you are using R2016b or later, you can use jsondecode to convert your JSON data into a struct. You can then modify the fields you want, change the value, and re-encode as json using jsonencode.

If your data is in a file, you can read the contents of the file in as a string prior to decoding with jsondecode

fid = fopen('filename.json', 'r');
str = fread(fid, '*char').';
fclose(fid);
J = jsondecode(str);

% Change the value
J.Matlab_NX.n1.Geometrieparameter.Breite = 3

If you are using older versions of MATLAB, the JSONlab File Exchange submission is very excellent and will also transform your data into a struct.

It's worth noting that with either of these methods, the fieldnames will have to be converted to valid fieldnames so spaces, hypens, etc. may not be preserved as you expect.

Sign up to request clarification or add additional context in comments.

Comments

1

Just flagging that the most efficient way to read and parse a JSON file is through a combination of jsondecode and fileread.

Instead of opening and closing the file "manually", just rely on fileread, which will load its contents in memory as a character vector.

contents = jsondecode(fileread(file_path))

Comments

0

As of 2014b you can also use the internal functions matlab.internal.webservices.fromJSON() and matlab.internal.webservices.toJSON() to convert a JSON string to Matlab data structures and back to JSON.

Your example would then read:

obj = matlab.internal.webservices.fromJSON( fileread( 'filename.json'));
obj.Matlab_NX.n1.Geometrieparameter.Breite = 3;
jsonStr = matlab.internal.webservices.toJSON( obj);
% write jsonStr to file if needed

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.