如何从json输出中检索值?

Nic*_*ick 2 javascript jquery json

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

[
    {
        "employees": {
            "education": "BE\/B.Tech"
        },
        "0": {
            "count": "1"
        }
    },
    {
        "employees": {
            "education": "MBA"
        },
        "0": {
            "count": "3"
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

我想找回员工的教育和计数.我试过,但我无法检索值.

我感谢任何帮助.

谢谢.

Fel*_*ing 10

假设您的JSON字符串在变量中$json,它是这样的:

var employees_list = JSON.parse($json);
Run Code Online (Sandbox Code Playgroud)

然后您可以通过以下方式访问信息:

employees_list[0].employees.education // gives you "BE\/B.Tech"
// and
employees_list[0]["0"].count // gives you 1.
Run Code Online (Sandbox Code Playgroud)

您也可以循环遍历数组并以education这种方式访问所有不同的方法.

更新:

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

[                                      // 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
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

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


你的JSON字符串的结构看起来有点奇怪.如果可以的话,你应该考虑以不同的方式构建它.

例如:

[
    {
        "education": "BE\/B.Tech",
        "count": "1"
    },
    {
        "education": "MBA"
        "count": "3"
    }
]
Run Code Online (Sandbox Code Playgroud)

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