简体   繁体   中英

How to search and fetch json row data by key using jQuery?

I have this JSON object:

{

"1234A":{
    "apcdiv_staffname":"MOHD NASA",
    "apcdiv_staffimage":"http://localhost/jknsapc/wp-content/uploads/2014/06/product-landing-layout-thumb.png",
    "apcdiv_workplace":"HOSPITAL",
    "apcdiv_grade":"U44",
    "apcdiv_position":"PEGAWAI FARMASI",
    "apcdiv_ic":"1234567"
},
"1234B":{
    "apcdiv_staffname":"MOHTAR",
    "apcdiv_staffimage":"http://localhost/jknsapc/wp-content/uploads/2014/06/product-landing-layout-thumb.png",
    "apcdiv_workplace":"HOSPITAL",
    "apcdiv_grade":"U44",
    "apcdiv_position":"PERGIGIAN",
    "apcdiv_ic":"7654321"
},

I want to search and fetch json row data by using key. For example, if I search using key 1234B , it will return the data belong to 1234B key. From there I can proceed to grab the data inside such as apcdiv_staffname

"1234B":{

"apcdiv_staffname":"MOHTAR",
"apcdiv_staffimage":"http://localhost/jknsapc/wp-content/uploads/2014/06/product-landing-layout-thumb.png",
"apcdiv_workplace":"HOSPITAL",
"apcdiv_grade":"U44",
"apcdiv_position":"PERGIGIAN",
"apcdiv_ic":"7654321"

}

How to achieve it using jQuery? I tried to Google but cannot find relevan answer, maybe because my choice of keyword. If using PHP array, I can simply using this code:

$object_row = $object['1234B'];
$apcdiv_staffname = $object_row['apcdiv_staffname'];

Thanks guys!

You really don't need jQuery for this. JSON can be accessed directly through javascript.

However if you want to use jQuery -

var obj = jQuery.parseJSON( '"1234A":{
    "apcdiv_staffname":"MOHD NASA",
    "apcdiv_staffimage":"http://localhost/jknsapc/wp-content/uploads/2014/06/product-landing-layout-thumb.png",
    "apcdiv_workplace":"HOSPITAL",
    "apcdiv_grade":"U44",
    "apcdiv_position":"PEGAWAI FARMASI",
    "apcdiv_ic":"1234567"
}' );

alert( obj.1234A );
alert( obj.1234A.apcdiv_staffname );

More Information

https://api.jquery.com/jquery.parsejson/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM