Save Selection as json

Hi, I’d like to save diagram.selection as json template so I can reuse it in the diagram.
Or do you have any other way to save selection data in db except json format?
Thanks.

That depends on what you mean by “so I can reuse it in the diagram”.

GoJS doesn’t support any kind of serialization except JSON-formatted text.


As you can see here, I’m saving diagram as templates so I can drag-drop into diagram.
I know how to save entire diagram as json.
But I haven’t found solution for saving only selected parts.
I’d like save selection, not whole diagram as template so I can save it in db and reuse it.

I’m not sure what you mean. There are several possibilities. Have you seen these samples?

https://gojs.net/extras/addToPalette.html

No, this shouldn’t be palette. Your references are all for palette. Please review this video: https://www.loom.com/share/970d11db75b64cb8a57b7a1385030422
So this is list of templates (html list, not gojs palette).
And each template saves diagram json data when user saves current diagram as template so users can drag and drop from templates list to paste it into his diagram.

Here, I know gojs supports model.toJson() to export whole model data into json, however, I want to export selected parts (digram.selection) into json data so I can save it as template.
Does this make sense?

OK. Whether you use a GoJS Diagram (such as a Palette) or not, the idea is basically the same – you just need some data represented by a collection of Parts, such as the Diagram.selection collection.

There are lots of ways to do that. Perhaps easiest is to make a copy of the model by calling Model.copy, copy the data that you want to it, and them serialize the model using Model.toJson. Assuming myDiagram is your current Diagram:

  function writeJson(coll) {  // assume COLL is a collection of Parts
    var tempDiag = new go.Diagram();
    tempDiag.model = myDiagram.model.copy();  // doesn't copy data
    myDiagram.copyParts(coll, tempDiag, false);
    return tempDiag.model.toJson();
  }

  function addJson(str) {  // assume STR is JSON-formatted output of Model.toJson()
    var newModel = go.Model.fromJson(str);
    var tempDiag = new go.Diagram();
    tempDiag.model = newModel;
    var coll = new go.Set();
    coll.addAll(tempDiag.nodes);
    coll.addAll(tempDiag.links);
    coll.addAll(tempDiag.parts);
    myDiagram.commit(function(diag) {
      tempDiag.copyParts(coll, diag, false);
    }, "added some parts");
  }

12 posts were split to a new topic: Calling makeSvg on Diagram returned null