3

I have a json which has a key "tag", which is returning data like this "tags": "jname,gender,city"

but i want to append these value in separate span like below

<div class="info">
<span>jname</span><span>gender</span><span>city</span>
</div>

I am trying with this

 $.getJSON("data.json", function(tagsposts) {

        var items = [];
    splitsVal = tag.split(",");
    for (var i = 0; i < splitsVal.length; i++) {
       obj.push({name:splitsVal[i]});
        obj[i] = '<span>' + obj[i] + '</span>';
        $('.tags-div').append(obj[i])
    }
   $.each(tagsposts, function(key, val) {
       items.push('<a href="#">' + val['tags'] + '</a>');
   });
   $('#tagsposts').append(items.join(""));
});

Am I doing correct

Sajal
  • 305
  • 1
  • 5
  • 17

1 Answers1

1

You're trying to split an undefined variable:

function(tagsposts) {
    var items = [];
    splitsVal = tag.split(","); // but tag doesn't exist...

(If you look at your browser console, which you should get into the habit of doing, you'll get a very clear message about why this isn't working: "ReferenceError: Can't find variable: tag".)

Since you haven't provided your JSON it's not possible to say exactly how to fix this. Assuming the full JSON is of the form

{"tag": "foo,bar,baz"}

then you would want

splitsVal = tagsposts.tag.split(",")

If there's more structure than that inside the JSON, you'll need to crawl down through that parsed object to find the "tag" value(s) you need.

There are lots of other problems here, however.

You also try to push onto an undefined array named obj; you'd need at least a var obj = [] outside that for loop. Though it's not clear why you're using obj at all, or trying to draw an object {name: val} into the DOM instead of just the value. What you're trying to do is just read splitsVal[i] so you can just do this:

for (var i = 0; i < splitsVal.length; i++) {
    $('.tags-div').append('<span>'+splitsVal[i]+'</span>')
}

And you try to iterate over tagsposts as if it's an array when generating the #tagsposts contents. (Is your JSON an array? If so you need to iterate over it when getting the tag values too.)

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53