How can I access the properties of my JSON object

2019-09-01 14:18发布

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.

1条回答
虎瘦雄心在
2楼-- · 2019-09-01 14:55

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: ...]
查看更多
登录 后发表回答