Thread7
Thread7

Reputation: 1090

Iterate through JSON with JQuery

I want to get the color names and hex values from some json data that I am retrieving from an external source. I created a jsfiddle to work through it but I am doing something fundamentally wrong because I don't even get to alert('hi'); Ideally I would like a list of the three color names with hex value beside it: Eg.

JSFiddle here: https://jsfiddle.net/Thread7/vp01m13x/2/

HTML:

<ul id="groups">
<li>Test</li>
</ul>

Javascript:

jsonval = '[{"category":"Exterior","options":[{"id":"200421460","name":"Brilliant Black","colorChips":{"primary":{"hex":"000000"}}},{"id":"200421466","name":"Ice Silver Metallic","colorChips":{"primary":{"hex":"C3C3C3"}}},{"id":"200421462","name":"Scuba Blue Metallic","colorChips":{"primary":{"hex":"2E3F59"}}}]}]';
var cardata = JSON.parse(jsonval);
$.each(cardata.options, function(o, valo) {
  alert('hi');
  $('<li>' + valo + '</li>').appendTo($grouplist);
});

Upvotes: 0

Views: 45

Answers (2)

xyhhx
xyhhx

Reputation: 6664

It's just a small problem with your JSON string. You have it wrapped in an array. You are trying to iterate cardata.options - which doesn't exist.

Two ways to fix this:

  1. Either remove the outer array (the [ and ] outside your string)
  2. Iterate over cardata[0].options

Still not behaving, yet...

So it's still not working in your fiddle. This is because of a reference to $grouplist which (at least in the fiddle linked in the question), does not exist.

Either remove the line referencing it, or you can add var $grouplist = $('ul'); at the top of the script.

Then it will work:

enter image description here

For future reference

You can easily test JSON strings out by popping that string into any popular web browser's debugging tools:

enter image description here

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227180

cardata.options doesn't exist because cardata is an array containing a single element, an object.

Then inside your $.each, valo will be an object. You'll need to use valo.id, valo.name, etc.

$.each(cardata[0].options, function(o, valo) {
    console.log(valo.id);
});

Here's an updated version of your demo:

var jsonval = '[{"category":"Exterior","options":[{"id":"200421460","name":"Brilliant Black","colorChips":{"primary":{"hex":"000000"}}},{"id":"200421466","name":"Ice Silver Metallic","colorChips":{"primary":{"hex":"C3C3C3"}}},{"id":"200421462","name":"Scuba Blue Metallic","colorChips":{"primary":{"hex":"2E3F59"}}}]}]';

var $grouplist = $('#groups');

var cardata = JSON.parse(jsonval);
$.each(cardata[0].options, function(o, valo) {
  $('<li style="color:#' + valo.colorChips.primary.hex + ';">' + valo.name + '</li>').appendTo($grouplist);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="groups"></ul>

Upvotes: 2

Related Questions