简体   繁体   中英

List part of data in JSON file using php or javascript

anyone know how to list some/part of data from json file using php or javascript?

example if i using sql i must do code

select email from employees where name='Shyam'

but for json i don't have any clue how to do it.

{"employees":[  
    {"name":"Shyam", "email":"shyamjaiswal@gmail.com", "job":"police"},  
    {"name":"Bob", "email":"bob32@gmail.com", "job":"athelic"},  
    {"name":"Jai", "email":"jai87@gmail.com", "job":"king"}  
]}  

by referring data above, i only want to select email where name=shyam by using php/javascript from json file.

With Javascript you could do something like that:

 const data = {"employees": [ {"name":"Shyam", "email":"shyamjaiswal@gmail.com", "job":"police"}, {"name":"Bob", "email":"bob32@gmail.com", "job":"athelic"}, {"name":"Jai", "email":"jai87@gmail.com", "job":"king"} ]}; const result = data.employees.filter(employe => employe.name === "Shyam"); console.log(result);

And with PHP you can do that:

$data = json_decode('{"employees": [  
  {"name":"Shyam", "email":"shyamjaiswal@gmail.com", "job":"police"},  
  {"name":"Bob", "email":"bob32@gmail.com", "job":"athelic"},  
  {"name":"Jai", "email":"jai87@gmail.com", "job":"king"}  
]}', true);

$result = array_filter($data['employees'], function ($employee) {
    return $employee['name'] === 'Shyam';
});
var_dump($result);

In PHP you can do something like this.

$json = '{"employees":[  
    {"name":"Shyam", "email":"shyamjaiswal@gmail.com", "job":"police"},  
    {"name":"Bob", "email":"bob32@gmail.com", "job":"athelic"},  
    {"name":"Jai", "email":"jai87@gmail.com", "job":"king"}  
]} ';

$jsonArray = json_decode($json, true);
$emails = [];

foreach ($jsonArray['employees'] as $item){
    if ($item['name'] == "Shyam") {
        $emails[] = $item['email'];
    }
}

Somethink like this (JS)?

      const getEmail = (json, name) => {
        const row = json.employees.find(e => e.name === name);
        return row ? row.email : null;
      }

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