17

How can you convert an array of strings represented in JSON format and convert this to an HTML bulleted list using jQuery?

4
  • 1
    Can you add an example of your JSON structure? Commented Nov 15, 2010 at 22:15
  • api.jquery.com/jQuery.getJSON Commented Nov 15, 2010 at 22:19
  • @Switz, getJSON is how I will get the data - not clear on how to convert one of the arrays into a list Commented Nov 15, 2010 at 22:20
  • See also: stackoverflow.com/questions/8806047/… Commented Apr 3, 2015 at 5:58

6 Answers 6

34
var ul = $('<ul>').appendTo('body');
var json = { items: ['item 1', 'item 2', 'item 3'] };
$(json.items).each(function(index, item) {
    ul.append(
        $(document.createElement('li')).text(item)
    );
});

As far as fetching the JSON from your server using AJAX is concerned you could use the $.getJSON() function.

Live demo.

Sign up to request clarification or add additional context in comments.

2 Comments

I've never seen jsfiddle.net before. I approve.
@climbage, it's a very good site allowing fast javascript mockups supporting popular frameworks.
6
<script language="JavaScript" type="text/javascript">

// Here is the code I use.  You should be able to adapt it to your needs.

function process_test_json() {
  var jsonDataArr = { "Errors":[],"Success":true,"Data":{"step0":{"collectionNameStr":"ideas_org_Private","url_root":"http:\/\/192.168.1.128:8500\/ideas_org\/","collectionPathStr":"C:\\ColdFusion8\\wwwroot\\ideas_org\\wwwrootchapter0-2\\verity_collections\\","writeVerityLastFileNameStr":"C:\\ColdFusion8\\wwwroot\\ideas_org\\wwwroot\\chapter0-2\\LastFileName.txt","doneFlag":false,"state_dbrec":{},"errorMsgStr":"","fileroot":"C:\\ColdFusion8\\wwwroot\\ideas_org\\wwwroot"}}};

var htmlStr= "<h3 class='recurse_title'>[jsonDataArr] struct is</h3> " + recurse( jsonDataArr );
alert( htmlStr );
$( document.createElement('div') ).attr( "class", "main_div").html( htmlStr ).appendTo('div#out');
$("div#outAsHtml").text( $("div#out").html() ); 
}
function recurse( data ) {
  var htmlRetStr = "<ul class='recurseObj' >"; 
  for (var key in data) {
        if (typeof(data[key])== 'object' && data[key] != null) {
            htmlRetStr += "<li class='keyObj' ><strong>" + key + ":</strong><ul class='recurseSubObj' >";
            htmlRetStr += recurse( data[key] );
            htmlRetStr += '</ul  ></li   >';
        } else {
            htmlRetStr += ("<li class='keyStr' ><strong>" + key + ': </strong>&quot;' + data[key] + '&quot;</li  >' );
        }
  };
  htmlRetStr += '</ul >';    
  return( htmlRetStr );
}

</script>
</head><body>
<button onclick="process_test_json()" >Run process_test_json()</button>
<div id="out"></div>
<div id="outAsHtml"></div>
</body>

<!-- QUESTION: Maybe some one with more jquery experience 
could convert this to a shorter / pure jquery method -->

Comments

5

A JSON string like that would look like:

'["foo","bar","base","ball"]'

You can parse that into an Javascript array object by calling JSON.parse(), iterate over that array and insert the strings.

var jsonstring = '["foo","bar","base","ball"]',
    arr = JSON.parse(jsonstring),
    len = arr.length;

while(len--) {
    $('<li>', { 
        text:   arr[len]
    }).appendTo('ul');
}

Comments

2

Use jQuery jPut plugin. Just create a html template & call your json file. you can also call the ajax file through jPut (ajax_url)

http://plugins.jquery.com/jput/

<script>
    $(document).ready(function(){
        var json = [{"name": "item1","link":"link1"},{"name": "item2","link":"link2"}];

          //jPut code 
          $("#menu").jPut({
            jsonData:json,
            name:"template",
          });
    });
</script>

<body>    
        <!-- jput template, the li that you want to append to ul-->
        <div jput="template">
           <li><a href="http://yourdomain.com/{{link}}">{{name}}</a></li>
        </div>

        <!-- your main ul -->
        <ul id="menu">
        </ul>
</body>

3 Comments

jput is not a valid attribute.
@Benio Add jput.js in your HTML.
jput, as you show in example code, is not a valid attribute. If you want to use custom attribute, you should use a custom data attribute, like data-jput, otherwise it's not a valid HTML code.
0

If your json strings are in stringArr:

$.each(stringArr, function(idx, val) {
   $('<li></li>').html(val);
}

or something among these lines should do it.

Comments

0

Something like this maybe? I haven't tested it, but it should work.

ul = $("<ul/>");
$(json_arr).each(function(){
    $("<li/>").text(this).appendTo(ul);
});

// add ul to DOM

Comments

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.