How exactly to use fromJson?

I’m trying to populate a doc from certain (rather huge) content I already have (and which I converted to JSON format that is similar to that produced by toJSON, but I cannot figure out how to use fromJSON. Here’s a rather trivial example: consider the following trivial.js:

const {Schema} = require("prosemirror-model")
const {EditorView} = require("prosemirror-view")
const {EditorState} = require("prosemirror-state")
window.EditorState = EditorState
window.trivialSchema = new Schema({
    nodes: {
        doc: {content: "paragraph+"},
        paragraph: {
            content: "text*",
            toDOM: () => ["p", 0],
        text: {inline: true},
window.view = new EditorView(document.body, {
    state: EditorState.create({
        schema: trivialSchema

(put everything on window to debug from browser console). Now if I try:

window.EditorState.fromJSON({'schema': window.trivialSchema}, window.view.state.doc.content.toJSON())

I get an error like:

Uncaught TypeError: Cannot read property 'marks' of undefined
    at Function.Node.fromJSON (trivial_bundle.js:2237)
    at trivial_bundle.js:4424
    at Array.forEach (<anonymous>)
    at Function.fromJSON (trivial_bundle.js:4422)
    at <anonymous>:1:20

So it doesn’t even seem to accept its own JSON (or more likely, I’m using it incorrectly). How can I populate my doc with the JSON content I have?

Nevermind, I obviously wasn’t thinking clearly. You obviously can’t call toJSON and fromJSON of different types and expect it to work. This works:

window.view.state.doc.constructor.fromJSON(window.trivialSchema, window.view.state.doc.toJSON())

or more elaborately:

window.view.state.doc.constructor.fromJSON(window.trivialSchema, JSON.parse(JSON.stringify(window.view.state.doc.toJSON())))

Now looking up how to update an existing doc with a new one…

The approach that I’ve been using so far is to define a schema object and pass the JSON document to schema.nodeFromJSON.

Giving the result of that function to a new EditorState seems to work pretty well.

1 Like

Thanks both of you @shreevatsa and @copperwall for your questions and hints.

Saved me a lot of time.


1 Like