如何使用javascript拆分此json数据? [英] how to split this json data using javascript?

查看:159
本文介绍了如何使用javascript拆分此json数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 third p tag to display it in the html page. Could you please anyone help me on this split?Could you please spilit the each content.rendered from array of json as mentioned in the sippet?

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

推荐答案

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

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
}

这篇关于如何使用javascript拆分此json数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆