thunderer/Shortcode

[question] Convert content with shortcodes into Json string ?

Titipox opened this issue · 2 comments

Hello,

Thank you for your shortcode library first, we use it for our works in our php framework :)

I have a question : is there a way to convert all shortcodes from a content (saved into a database for example) into a JSON string like the serialize method ?
We develop a CMS for our use, and we saved the blocks into shortcodes in database. But to edit the blocks (in page edition), we need to convert the shortcodes into JSON to setup our CMS JS Builder at start.

Saved code example :
[text style="class1 class2"]blabla bla[/text][section][grid layout="1/2" style="class3"][col][media id="15][text]1st col text[/text][/col][col][text]2nd col text[/text][/col][/grid][section]

=> JSON

{
  "name": "text",
  "parameters": { "style": "class1 class2" },
  "content": "blabla bla"
},
{
  "name": "section",
  "parameters": {},
  "content": [
    {
      "name":"grid",
      "parameters": { "layout": "1/2", "style": "class3" },
      "content": [
        {
          "name": "col",
          "parameters": {},
          "content": [
            {
              "name": "media",
              "parameters": { "id": "15" },
              "content" : ""
            },
            {
              "name": "text",
              "parameters": {},
              "content" : "1st col text"
            }
          ]
        },
        {
          "name": "col",
          "parameters": {},
          "content": [
            {
              "name": "text",
              "parameters": {},
              "content" : "2nd col text"
            }
          ]
        }
      ]
    }
  ]
}

Thank you.

Hi @Titipox - you can use one of the parsers (I recommend RegularParser) to extract a list of ParsedShortcode instances which will tell you the exact matched text offset and details of the shortcode at that position. You can then convert these details to your format of choice and save them in the database. I see that you also want to save information about nested shortcodes. In that case please get the content of each parsed shortcode and parse it again to get the list. You need to do it recursively to create the whole tree.

Hi @thunderer , thank you for your answer. We did it by parsing our full shortcodes content recursively. We'll implement your method to make it properly :)
Best regards.