2015-11-24 91 views
1

我想提出一个API的调用返回类似于此:HTML标记解析JSON数据在JavaScript

{ 
    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-tags和奇怪的'&#039我相信这是一个撇号。我玩过JSON.stringify,但是如果我将整个响应串联起来,解析起来就非常困难。 (因为我修改了大部分数据以保持简洁)另外,如果仅对正文进行字符串化,则会返回相同的字符串。提前致谢。我将围绕回答问题。

+1

您可以添加一个关于如何使用它的例子吗? – RageAgainstTheMachine

回答

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; 

没有任何类型的解析,str ingifying etc - >http://jsfiddle.net/zdLbp89z/

+0

感谢您发现。答案实际上是完全不同的,但我试图快速修剪它。 – Steez

0

您应该使用innerHtml功能,它

在JS你可以做这样的:

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