What is the best way to convert EditorJs text editor json to html elements?
Asked Answered
D

9

24

I'm trying to convert EditorJs output to Html. EditorJs outputs 'clean' data like this:

{
  "time": 1589987527499,
  "blocks": [
    {
      "type": "embded",
      "data": {
        "service": "youtube",
        "source": "https://www.youtube.com/watch?v=JbqGYgI3XY0",
        "embed": "https://www.youtube.com/embed/JbqGYgI3XY0",
        "width": 580,
        "height": 320,
        "caption": ""
      }
    },
    {
      "type": "image",
      "data": {
        "file": {
          "url": "http://localhost/uploads/images/1.jpg"
        },
        "caption": "",
        "withBorder": false,
        "stretched": false,
        "withBackground": false
      }
    },
    {
      "type": "header",
      "data": {
        "text": "test",
        "level": 2
      }
    }
  ],
  "version": "2.17.0"
}

how can I convert to this to raw HTML? Do I have to convert this manually?

Dibble answered 20/5, 2020 at 15:16 Comment(0)
F
18

The 'editorjs-html' library can help you parse you Json data to HTML. It provides some basic parser functions, but also allows you to override and define your own parser functions. It is framework independent, so you can use it anywhere.

The README repository has some good information, but you can also see some examples here, https://medium.com/@pavittarx/rendering-json-from-editor-js-to-html-bfb615ee78c4

Firer answered 17/6, 2020 at 14:21 Comment(3)
This is good. But it lacks the youtube embed, which I think is the highlight of the editorjs plugin.Dibble
You can always write your own parser functions. Read the docs!Firer
pavittarx did the trick for me :) <3Uncanny
D
10

I found a function to do it and I made a modification of my own. I think it can be improved but right now this is the best that I got.

  convertDataToHtml(blocks) {
      var convertedHtml = "";
      blocks.map(block => {
        
        switch (block.type) {
          case "header":
            convertedHtml += `<h${block.data.level}>${block.data.text}</h${block.data.level}>`;
            break;
          case "embded":
            convertedHtml += `<div><iframe width="560" height="315" src="${block.data.embed}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></div>`;
            break;
          case "paragraph":
            convertedHtml += `<p>${block.data.text}</p>`;
            break;
          case "delimiter":
            convertedHtml += "<hr />";
            break;
          case "image":
            convertedHtml += `<img class="img-fluid" src="${block.data.file.url}" title="${block.data.caption}" /><br /><em>${block.data.caption}</em>`;
            break;
          case "list":
            convertedHtml += "<ul>";
            block.data.items.forEach(function(li) {
              convertedHtml += `<li>${li}</li>`;
            });
            convertedHtml += "</ul>";
            break;
          default:
            console.log("Unknown block type", block.type);
            break;
        }
      });
      return convertedHtml;
    }
Dibble answered 3/10, 2020 at 12:59 Comment(0)
I
8

Editorjs outputs clean data and maintainers have not implemented readOnly functionality yet, to get the HTML out of it. So, the only solution is to write a conversion functionality by yourself, but I've created a package for this purpose. editorjs-parser. It supports most block types and You can also provide your own custom parser for any type of block. It supports :

  • Paragraph
  • Header
  • Table
  • Raw
  • Delimiter
  • Code
  • Quote
  • List
  • Embed
  • Image

It is also configurable.

Intertexture answered 2/11, 2020 at 9:46 Comment(1)
They now have a readOnly option but its not SEO-Friendly so I guess some library like this implemented from the server side will allow us to use server side renderingPropitiatory
S
3

I don't know why need to convert to html, you can have clean data at server and render it as readOnly now through editor js

default readOnly attribute is false.

Here is example html file provided by editorjs check this html

Note : Since I came to this question only reason was earlier editorjs was not having readOnly mode. Currently it supports readOnly mode. So my requirements were satisfied. my need was satisfied. If there is any other reason. Above answers look pretty good.

Stellarator answered 26/1, 2021 at 10:28 Comment(1)
That is a viable option, however you are essentially putting additional load time on your page by adding another js resource request when loading the editor js on the preview page.Dibble
S
2

you can use this npm install @son_xx/editor-js-parser

Severalty answered 18/11, 2020 at 4:12 Comment(1)
Links are not considered as answers but comments to the question.Supertonic
C
2

I used an npm package editorjs-react-renderer, which proved very helpful and easy to go. Before you start using it you need to get the data object which is of the following form

 {
      "time": //some value here,
      "version": //some value here,
      "blocks": [
        {
          "type": "paragraph",
          "data": {
            "text": "Start writing here !!!",
            "level": 1
          }
        },
      ]
    }

Now install the package by

npm i editorjs-react-renderer

And then import the following in the respective file

import Output from 'editorjs-react-renderer';

OR

const Output = require('editorjs-react-renderer');

OR if you get the error like Window is not defined or you are using the React/Next JS, import using this method

import dynamic from "next/dynamic";
let Output = dynamic(() => import('editorjs-react-renderer'), {ssr: false});

And then finally, use the data={} object of the above format and Output component to render the HTML from the JSON

    <div>
        <Output data={ data_of_correct_format_containing_blocks } />
    </div>

The package available is EditorJS-React Renderer (ERR) and the following is a very good demo by shucoll

Construct answered 20/5, 2022 at 13:54 Comment(1)
Image not showing up. Image type has changed in editor jsLaclair
A
1

You need to convert it manually but i would create something like a engine that has components based on the "type" for example if it's type: image it would render a component that displays an image from the "data.file.url" you can also add more features to this image component, you might want a caption, then you have that data.

Same goes for the "embed" type, this one would have a "child" component that gets rendered depending on the "data.service" condition, in this case it's YouTube and then it would make a embeded youtube video with the source of "data.source".

This might help aswell: https://github.com/codex-team/editor.js/issues/676

Aurea answered 6/6, 2020 at 19:3 Comment(0)
P
1

there are plenty of solutions already but I would love to contribute with "my own".

This is a fork of another project that adds support for new blocks such as:

  • SimpleImage
  • linkTool

https://www.npmjs.com/package/@herii/editorjs-parser

You can install it with yarn or npm, its up to you:

 yarn add @herii/editorjs-parser



const edjsParser = require("editorjs-parser");

const parser = new edjsParser();
const HTML = parser.parse(editorjs_data); // editor_js_data is the object that contains the blocks genrated by editorjs

Here is an example of the data you have to pass to parser.parse()

Here is an example of linkTool which is a new block I added support for. (The HTML was generated by this parser and the styles are shown in a sandbox I created.)

enter image description here

Hope it helps you!

Propitiatory answered 6/9, 2022 at 5:55 Comment(0)
G
0

You can use the editorjs-html package to convert the native editorjs JSON content to HTML.

I have created some utility functions for this:

import editorJsHTML from "editorjs-html";

const edjsParser = editorJsHTML()

/**
 * Parse editorjs JSON string to array of HTML code
 * @param data - editorjs JSON string
 * @returns {Array<string>|*[]}
 */
export function parseEditorJs(data) {
  if (typeof data === 'undefined' || data === null) {
    return []
  }
  let content = data
  if(typeof data === 'string' ) {
    content = JSON.parse(data)
  }
  return edjsParser.parse(content)
}

/**
 * Parse editorjs JSON string to HTML code
 * @param data - editorjs JSON string
 * @returns {string} with HTML code
 */
export function parseEditorJsToHtml(data) {
  const array = parseEditorJs(data)
  return array.join("\n")
}

/**
 * Parse editorjs JSON string to plain text
 * @param data - editorjs JSON string
 * @returns {string} with plain text
 */
export function parseEditorJsToText(data) {
  const html = parseEditorJsToHtml(data)
  // Convert html to text
  return html.replace(/<[^>]*>?/gm, '').trim();
}

For these functions to work, make sure that you install the package first:

yarn add editorjs-html
Greenland answered 15/11, 2023 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.