I'm trying to parse a JSON structure, The json structure looks something like this:
{
children: [
{
type: "p",
children: [{
text: ""
}]
},
{
type: "social_embed",
children: [{
text: ""
}]
source_url: "some_url"
},
{
type: "p",
children: [{
type: "p",
children: [{
type: "p",
children: [{
text: ""
}]
}]
}]
},
]
}
The output will look like:
{
children: [
{
type: "p",
children: [{
text: ""
}]
},
{
type: "p",
children: [{
text: "some_url"
}]
},
{
type: "p",
children: [{
type: "p",
children: [{
type: "p",
children: [{
text: ""
}]
}]
}]
},
]
}
This is the code I'm trying:
if (currentBlock.type == "card" || currentBlock.type =="card_body")
{
parsedBlocks.map((block: any, index: any) => {
block.children = parseBlocks(block.children)
})
console.log("Blocks after parsing", parsedBlocks)
editor.insertFragment(parsedBlocks);
return true
}
const parseBlocks = (blocks: any): any => {
blocks.forEach((block: any) => {
console.log("Block ", block)
if (block.type == "social_embed") {
const newBlock = {
type: "p",
children: [
{
text: block.source_url
}
]
}
blocks[blocks.indexOf(block)] = newBlock
}
if (block.children) {
return parseBlocks(block.children)
}
})
return blocks
}
I want to recursively traverse all children until there is no children property in the object and when I encounter the object with type: "social_embed" I want to replace it with type : "p" and the text as source_url and modify the entire array, The children can have unlimited nesting but the social_embed can't have anything inside it's children other than {text: ""}