2015-11-24 137 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;