0

Yeah I've been vaguely trying to use this questions example to test something out with jsfiddle. I'm looking to build a JQuery sortable widget, but first I need to find out how I can access properties in the object I'm creating - drawing up a bit of a blank at the moment after a lot of messing about with it!

Live Fiddle!

$('#ParentCategoryId').change(function() {
    var data =
{
"categories": {
    "category1": {
        "Name": "Maps",
        "Id": 3,
        "orderInList": 1
    },
    "category2": {
        "Name": "Books",
        "Id": 2,
        "orderInList": 2
    }
}
};

$.ajax({
    url: 'http://jsfiddle.net/echo/jsonp/',
    dataType: 'jsonp',
    data: data,
    success: function(data) {
        show_response(data);
    },
    type: 'GET'
});
});            

function show_response(data) {
    $.each(data, function()
    {        
        alert(/**How could I access say, category1's Name property in here?**/);
    };   

Edit 1

Didn't get the full Jsfiddle link sorry, saved and edited it in.

Edit 2

Used JsonLint to create valid Json. Now I can get the alert to execute, but I'm unsure how to access the properties within!

Edit 3

Updated Jsfiddle link to latest version.

Community
  • 1
  • 1
Kiada
  • 679
  • 3
  • 15
  • 24
  • Pretty sure your JSON isn't valid. You're using the [] array notation to define an object. Should be using the {} notation. – Strelok Aug 13 '12 at 08:53
  • You're correct :) I was in the process of validating and correcting it after 'discovering' jsonlint when you commented :) – Kiada Aug 13 '12 at 09:01

1 Answers1

1

You need to parse the JSON string into an object:

function show_response(data) {
    data = $.parseJSON(data);
    $.each(data, function(position, value)
    {        
       alert(value.name);
    };

EDIT: Your fiddle has syntax errors. The JSON is not created as there is no toJSON method in jQuery. In order to read your categories using an each iterator, they need to be an array like:

categories = [name: "Book", value: ...], [name: "Movie", value: ...]
Telémako
  • 673
  • 3
  • 9
  • Thanks for that tip. What would I write in the alert box to output the Name property? this.Name doesn't work hrrmm. – Kiada Aug 13 '12 at 08:37
  • Your fiddle is full of errors and unfinished code, I don't know exactly what you are trying to do. Inside the each statement, you can access your object like this: `$.each(data, function(position, value) { alert(value);` – Telémako Aug 13 '12 at 09:02
  • Apologies for that, the JSON wasn't valid. This works now though thank you! – Kiada Aug 13 '12 at 09:28