6

I have problem understanding arrays and loops, therefore this task is a bit confusing to me. Here's my stuff;

JSON

{
"states": [
    { 
        "name":"johor" , 
        "command":"view_johor" }, 

    { 
        "name":"selangor" , 
        "command":"view_selangor" }, 

    { 
        "name":"melaka" , 
        "command":"view_melaka" }, 

    { 
        "name":"kuala lumpur" , 
        "command":"view_kl" }, 

    { 
        "name":"penang" , 
        "command":"view_penang" }
    ]
}

JAVASCRIPT

$(function(){

$.ajax({
    type        :   'GET',
    url         :   'scripts/list.json',
    async       :   false,
    beforeSend  :   function(){/*loading*/},
    dataType    :   'json',
    success     :   function(result){

                        $.each(result, function(index, val){
                            for(var i=0; i < val.length; i++){
                                var item = val[i];
                                console.log(item.name)
                                }
                        });         

                        },
   });
});

My problem is I don't know how to use the loop it so that my HTML will return like this:

<ul>
   <li><a href="#view_johor">Johor</a></li>
   <li><a href="#view_selangor">Selangor</a></li>
   <!-- and so on, dynamically depending on json... -->
</ul>

I can access the data via console.log(item.name) and such, but I can't manipulate the data so that it will display like I wanted. I don't even know the term to use to search for questions, as I know this is like basic array stuff....Thank you in advance for your help!

1
  • there are 100's of posts on this site....and many tutorials on web on how to parse json to html... do a bit more searching Commented Oct 27, 2013 at 5:30

5 Answers 5

8

u can do it :

 $(function(){

$.ajax({ 
  type : 'GET', 
  url : 'scripts/list.json', 
  async : false, 
  beforeSend : function(){/*loading*/},
  dataType : 'json', 
  success : function(result){
   var buffer="";
    $.each(result, function(index, val){ 

      for(var i=0; i < val.length; i++){ 
        var item = val[i]; 
        console.log(item.name);
        buffer+=" <li><a href='#"+item.name+"'>"+item.name+"</a></li> <li><a href='#"+item.command+"'>"+item.command+"</a></li>"; 
      } 
      $('ul').html(buffer);
    });
  }
 });
});
Sign up to request clarification or add additional context in comments.

4 Comments

Here's my console to you Can't find variable: buffer
Sorry. My bad. Forgot to create var = buffer up there.
Thanks @Vicky. I'll grow up to be a better developer thanks to you!
No! What if item.name contains an HTML entity?
0

Jquery can create elements and append to your documents with few lines of code.

You can create an empty list like this.

 var mylist=$("<ul></ul>");

Then inside your for loop, for each item, do something like this

mylist.append($("<li></li>").text(item.name));

And finally append your newly built list to your document to get it displayed:

mylist.appendTo($("body"));

Comments

0

I'm checked this script and this works properly:

var records = {
                "states": [
                    {
                        "name": "johor",
                        "command": "view_johor"
                    },

                    {
                        "name": "selangor",
                        "command": "view_selangor"
                    },

                    {
                        "name": "melaka",
                        "command": "view_melaka"
                    },

                    {
                        "name": "kuala lumpur",
                        "command": "view_kl"
                    },

                    {
                        "name": "penang",
                        "command": "view_penang"
                    }
                ]
            };

            $.each(records.states, function (key, val) {
                $('#ul').append($('<li>').text('name: ' + val.name + ', command: ' + val.command));
            });

and this is html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <ul id="ul"></ul>
</body>
</html>

Comments

0

This should work :

Get the json file you want to read from, make a list of items using the key and values of the json data.And finally add the list inside a ul and append it to body.

$.getJSON( "jsonFile.json", function( data ) {
    var items = [];
    $.each( data, function( key, val1 ) {
    $.each(val1, function(){
            items.push( "<li><a href=#'" + this.command + "'>" + this.name + "</a></li>" );     
        });
    });
    $( "<ul/>", {
        "class": "my-new-list",
        html: items.join( "" )
        }).appendTo( "body" );
});

2 Comments

U r missing # in href
Maybe I should convert items to string first? HTML printed [Object, Object] five times.
-1

Making very minor adjustments to your code,

var a = [];
$.each(result, function(index, val){
    for(var i=0; i < val.length; i++){
        var item = val[i];
        a.push(item);
    }
});

Now do something with all of the values in the array a.

EDIT:

In case that wasn't enough,

var list = $('<ui></ui>');
$.each(result.states, function(state) {
    var link = $('<a></a>').prop('href', state.command).text(state.name);
    ('<li></li>').append(link).appendTo(list);
});

list is the HTML you want (except for the name capitalization...I wasn't sure if the first letter should be capitalized, or the first letter of each word, so I left that alone).

4 Comments

-1 that change doesn't create html or steer OP in helpful direction
"I can access the data via console.log(item.name) and such, but I can't manipulate the data". Now he can manipulate the data.
@charlietfl, the responder here at worst deserves no vote, a negative vote is counter productive. My opinion.
It stemmed from my misinterpretation of "JSON to list" as "JSON to array" instead of "JSON to HTML list" (which, BTW is a bit like saying "XML to Http"...very specific)

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.