tags:

views:

70

answers:

2
+2  Q: 

jQuery with json

I have the following json code file named: sections.json

{
    "section1": { "priority": 1, "html": '<img src="../images/google.png" />'},
    "section2": { "priority": 2, "html": '<input type="button" value="Login" />'},
    "section3": { "priority": 3, "html": '<div>Some text</div>'},
    "section4": { "priority": 4, "html": '<div>Some text</div>'},
    "section5": { "priority": 5, "html": '<select><option>option1</option> <option>option2</option></select>'}
}

I am trying this in jquery code but alert is not working

$.getJSON("sections.json", function(json) {
    alert('h');
});
A: 

Seems to be invalid JSON so JQuery fails silently (see http://api.jquery.com/jQuery.getJSON/). Try http://www.jsonlint.com/ to validate your JSON file.

E.g. for section 1 the value for html should be "<img src='../images/google.png' />"

Check out this answer for an example of html tags in JSON: http://stackoverflow.com/questions/963448/html-tags-within-json-in-python

Daniel Lee
+1  A: 

Your JSON should be like this:

{
  "section1": { "priority": 1, "html": "<img src='../images/google.png' />"},
  "section2": { "priority": 2, "html": "<input type='button' value='Login' />"},
  "section3": { "priority": 3, "html": "<div>Some text</div>"},
  "section4": { "priority": 4, "html": "<div>Some text</div>"},
  "section5": { "priority": 5, "html": "<select><option>option1</option> <option>option2</option></select>"}
}

The values must be double quoted to be valid JSON, single quotes won't do :) As of jQuery 1.4, invalid JSON is no longer allowed by default (they added some additional checks to ensure it's valid, and the JSON in your question is getting blocked by those :)

Nick Craver