开发者

How to retrieve value from json output?

开发者 https://www.devze.com 2023-01-08 07:36 出处:网络
I am new to json. I have json output that looks like this [ 开发者_JAVA技巧{ \"employees\": { \"education\": \"BE\\/B.Tech\"

I am new to json. I have json output that looks like this

[
    开发者_JAVA技巧{
        "employees": {
            "education": "BE\/B.Tech"
        },
        "0": {
            "count": "1"
        }
    },
    {
        "employees": {
            "education": "MBA"
        },
        "0": {
            "count": "3"
        }
    }
]

I want to retrieve the employee's education and the count. I have tried but i am not able to retrieve the values.

I appreciate any help.

Thanks.


Assuming your JSON string is in a variable $json, it goes like this:

var employees_list = JSON.parse($json);

Then you can access the information via:

employees_list[0].employees.education // gives you "BE\/B.Tech"
// and
employees_list[0]["0"].count // gives you 1.

You can also loop over the array and access all the different education this way.

Update:

To better demonstrate which expression accesses which information:

[                                      // employees_list
    {                                  // employees_list[0]
        "employees": {                 // employees_list[0].employees
            "education": "BE\/B.Tech"  // employees_list[0].employees.education
        },
        "0": {                         // employees_list[0]["0"]
            "count": "1"               // employees_list[0]["0"].count
        }
    }, 
    {                                  // employees_list[1]
        "employees": {                 // employees_list[1].employees
            "education": "MBA"         // employees_list[1].employees.education
        },
        "0": {                         // employees_list[1]["0"]
            "count": "3"               // employees_list[1]["0"].count
        }
    }
]

Generally employees_list[0].employees is the same as employees_list[0]["employees"] but this does not work for numbers, because properties and variables are not allowed to start with numbers. So you can only use employees_list[0].["0"] and not employees_list[0].0.


The structure of your JSON string looks a bit strange though. You should consider to structure it differently if you can.

For example:

[
    {
        "education": "BE\/B.Tech",
        "count": "1"
    },
    {
        "education": "MBA"
        "count": "3"
    }
]

The "0" key in your original JSON string seems to serve no purpose and just complicates the access.

0

精彩评论

暂无评论...
验证码 换一张
取 消