Steez
Steez

Reputation: 229

Parsing JSON data with html tags in javascript

I am making a call to an API that returns something similar to this:

{
  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>
           }
}

I can access the data no problem, however when I attempt to add the body of the story to the page it still has the p-tags and the weird '&#039 which i'm confident is a apostrophe. I have played around with JSON.stringify, however if I stringify the entire response, it is extremely difficult to parse. (As I have modified much of the data to keep it brief) Additionally if stringify just the body, it returns the same string. Thanks in advance. I will be around to answer questions.

Upvotes: 1

Views: 153

Answers (2)

davidkonrad
davidkonrad

Reputation: 85518

If we assumed the above actually was valid JSON

  • problems with not quoted attributes / key names
  • missing end quotes
  • missing , and ending }
  • malformed html entity &39

so it looked like this :

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

Then there would be no problem at all to do for example :

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

without any kind of parsing, stringifying etc -> http://jsfiddle.net/zdLbp89z/

Upvotes: 1

hurricane
hurricane

Reputation: 6724

You should use innerHtml function for it

In js you can do it like that:

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

Upvotes: 0

Related Questions