如何从json输出中检索值? [英] How to retrieve value from json output?

查看:106
本文介绍了如何从json输出中检索值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是json的新手.我有看起来像这样的json输出

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

[
    {
        "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.

感谢您的帮助.

谢谢.

推荐答案

假设您的JSON字符串位于变量$json中,则它如下所示:

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.

您还可以循环访问数组并以这种方式访问​​所有不同的education.

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

更新:

为了更好地演示哪个表达式访问哪些信息:

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
        }
    }
]

通常employees_list[0].employeesemployees_list[0]["employees"]相同,但这不适用于数字,因为属性和变量不允许以数字开头.因此,您只能使用employees_list[0].["0"] ,不能 employees_list[0].0.

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.

您的JSON字符串的结构看起来有些奇怪.如果可以的话,您应该考虑采用不同的结构.

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

例如:

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

原始JSON字符串中的"0"键似乎没有任何作用,只会使访问变得复杂.

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

这篇关于如何从json输出中检索值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆