Skip to content Skip to sidebar Skip to footer

How To Split This Json Data Using Javascript?

How to split this json data using javascript? And I want store content.rendered json in the different variables are description as first p tag, image as second p tag, file as thir

Solution 1:

First, you have to parse the JSON using JSON.parse then you'll need to parse the HTML stored in content.rendered.

Something like the following should work.

const str = `{
   "author": 1,
   "content": {
      "rendered": "<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>\\n<p><a href=\\"file.pdf\\"></a></p>\\n<p><img src=\\"image.jpg\\"/></p>",
      "protected": false
   }
}`
let json = JSON.parse(str)
let content = document.createElement('div')
content.innerHTML = json.content.rendered

let description = content.querySelector('p').innerText
let image = content.querySelector('img').src
let file = content.querySelector('a').href

let result = {
  description,
  image,
  file
}

Solution 2:

Probably, you want to parse data.

Firstly, JSON.parse()

Then, you need to parse the content.rendered (correct me,pls, if not). For this you can try:

let [, data, file, img] = data
  .split('<p>')
  .map(v => v.replace(/<\/p>/g,''));

data = data.trim();
file = file.match(/"(.*?)"/)[0]; // file.pdf
img= img.match(/"(.*?)"/)[0]; // image.jpg

Post a Comment for "How To Split This Json Data Using Javascript?"