如何使用javascript拆分此json数据?

时间:2018-08-19 20:11:05

标签: javascript json

如何使用javascript拆分此json数据?我想将content.rendered json存储在不同的变量中,将描述存储为第一个p标签,将图像存储为第二个p标签,将文件存储为第三个p标签,以将其显示在html中页。您可以请任何人在此拆分上为我提供帮助吗?您可以请参见sippet中提到的从json数组呈现的每个内容吗?

 [{
       "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
       }
    },
    {
       "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
       }
    },
    {
       "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
       }
    }]

2 个答案:

答案 0 :(得分:1)

首先,您必须使用JSON.parse解析JSON,然后需要解析content.rendered中存储的HTML。

类似以下的方法应该起作用。

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
}

答案 1 :(得分:0)

可能您想解析数据。

首先,JSON.parse()

然后,您需要解析content.rendered(如果没有,请对我进行修正)。为此,您可以尝试:

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