首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用javascript拆分这个json数据?

如何使用javascript拆分这个json数据?
EN

Stack Overflow用户
提问于 2018-08-20 04:11:05
回答 1查看 197关注 0票数 -1

如何使用javascript拆分这个json数据?我希望在不同的变量中存储content.rendered json作为第一个p标签,图像作为第二个p标签,文件作为第三个p标签,以便在html页面中显示它。你能在这个拆分上帮我吗?你能像在sippet中提到的那样,从json数组中分离出每个content.rendered吗?

代码语言:javascript
复制
 [{
       "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
       }
    }]

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-20 04:27:58

首先,必须使用JSON.parse解析JSON,然后需要解析存储在content.rendered中的超文本标记语言。

下面这样的代码应该可以工作。

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51921448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档