Newcoma
Newcoma

Reputation: 809

Get value from json in jQuery

I have this json

"urls": {
      "title1": {
        "url": "someurl1"
      },
      "title12": {
        "url": "someurl2"
      }
    }

I want get title and value of url out in an element for each. Something like this

$.each(value.urls, function (key, value) {
    $('.log-list-js').append('<a href="'+ title +'">'+ someurl +'</a>');
});

Hope it makes sense.

Can you help me ?

Upvotes: 1

Views: 88

Answers (3)

Ruwanka De Silva
Ruwanka De Silva

Reputation: 3745

Your json should be converted to object first, use JSON.parse method if you are having a json string. object should something like this

urls = {
      "title1": {
      "url": "someurl1"
      },
      "title12": {
        "url": "someurl2"
      }
    };

then your method is correct with some corrections to the code

$.each(urls, function(index, value){
    $('.log-list-js').append('<a href="'+ index +'">'+ value.url +'</a>');
});

here is the demo on jsfiddle

Upvotes: 0

Kaushik
Kaushik

Reputation: 2090

$('.log-list-js').append('<a href="' + value.urls[key].url + '">' + value.urls[key].url + '</a>');

This is format

Upvotes: 0

Anton
Anton

Reputation: 32581

Try this

   var values = {
        "urls": {
            "title1": {
                "url": "someurl1"
            },
            "title12": {
                "url": "someurl2"
            }
        }
    }
    for (var key in values.urls) {
        $('.log-list-js').append('<a href="' + values.urls[key].url + '">' + values.urls[key].url + '</a>');
    }

DEMO

Upvotes: 2

Related Questions