2

I need a simple example that has a json data and I have to parse it and render in html. Can someone suggest me a simple way to do this?

1
  • Not exactly sure what you're asking. Have you got a specific example? Commented Jan 9, 2012 at 11:29

2 Answers 2

5

You can create a string from an object in JavaScript like this...

var jsonString = JSON.stringify(myJsonObject);

Then you can use that string to apply to a html element. For example...

document.getElementById('myDivID').innerText = jsonString;

With JQuery you can update a DIV with the following...

$("#MyDiv").html(jsonString);
Sign up to request clarification or add additional context in comments.

Comments

1

I'm not entirely sure what you are asking. You do not have to use jQuery specifically to parse the object. All you need is standard JavaScript.

Given a JSON string, you can parse it into a JavaScript object using the JSON library

var myJSONObject = JSON.parse(myJSONString);

Or into a string from an object:

var myJSONString= JSON.stringify(myJSONObject);

If you are looking for the individual items of a JSON structure, then you can use a for loop:

for (var key in myJSONObject){
    alert(myJSONObject[key]);
}

I've alerted myJSONObject[key] in the above, however, you can do what you want with it.

You would use jQuery to select out the container into which you wanted the info to be displayed, as suggested in usefan's answer.

3 Comments

Don't have to use JQuery for what? I only mentioned it for updating a HTML element (to which you have offered no javascript alternative)
I'm reading that Sripaul wanted to know how to parse it, rather than stringify it, hence the for loop and no requriement for jQuery. Your answer is, of course entirely correct (although I would use .text() instead of .html() ) :-)
Ah yes, I see your point. I thought the idea was to display the data of a JSON object as text (I guess you can read the question either way)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.