在javascript

时间:2015-11-24 14:42:27

标签: json api parsing

我正在调用返回类似于此内容的API:

{
  node: {
    16981: {
       type: "story",
       title: "The day I found a dollar",
       body: "<p>Today i was going to the mall when I found a dollar</p><p>This wasn&39t just any dollar it was a magical dollar</p>
      }
    17005: {
       type: "story",
       title: "My Big Thanksgiving",
       body: "<p>Thanksgiving has always been one of my favorite hollidays</p><p>My favorite part of thanks giving is eating all of the food. I really like food</p><p>This year I&#039;m going to eat only turkey</p>
           }
}

我可以毫无问题地访问数据,但是当我尝试将故事的主体添加到页面时,它仍然具有p标签和奇怪的&#39;&#039我对此充满信心是撇号。我已经使用过JSON.stringify,但是如果我将整个响应字符串化,则解析起来非常困难。 (因为我修改了大部分数据以保持简洁)另外如果只是字符串化,它返回相同的字符串。提前致谢。我会回答问题。

2 个答案:

答案 0 :(得分:1)

如果我们假设上面实际上是有效的JSON

  • 未引用属性/密钥名称的问题
  • 缺少结束语录
  • 缺少,并结束}
  • 格式错误的html实体&39

所以它看起来像这样:

{
    "node": {
        "16981": {
            "type": "story",
            "title": "The day I found a dollar",
            "body": "<p>Today i was going to the mall when I found a dollar</p><p>This wasn&39t just any dollar it was a magical dollar</p>"
        },
        "17005": {
            "type": "story",
            "title": "My Big Thanksgiving",
            "body": "<p>Thanksgiving has always been one of my favorite hollidays</p><p>My favorite part of thanks giving is eating all of the food. I really like food</p><p>This year I&#039;m going to eat only turkey</p>"
        }
    }
}

然后根本不会有任何问题:

document.getElementById('content').innerHTML += json.node[17005].body;

没有任何解析,字符串化等 - &gt;的 http://jsfiddle.net/zdLbp89z/

答案 1 :(得分:0)

您应该使用innerHtml功能

在js中你可以这样做:

document.getElementById("#yourId").innerHTML = result.node.body;