skip to Main Content

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":"[email protected]", "job":"police"},  
    {"name":"Bob", "email":"[email protected]", "job":"athelic"},  
    {"name":"Jai", "email":"[email protected]", "job":"king"}  
]}  

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

3

Answers


  1. With Javascript you could do something like that :

    const data = {"employees": [  
      {"name":"Shyam", "email":"[email protected]", "job":"police"},  
      {"name":"Bob", "email":"[email protected]", "job":"athelic"},  
      {"name":"Jai", "email":"[email protected]", "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":"[email protected]", "job":"police"},  
      {"name":"Bob", "email":"[email protected]", "job":"athelic"},  
      {"name":"Jai", "email":"[email protected]", "job":"king"}  
    ]}', true);
    
    $result = array_filter($data['employees'], function ($employee) {
        return $employee['name'] === 'Shyam';
    });
    var_dump($result);
    
    
    Login or Signup to reply.
  2. Somethink like this (JS)?

          const getEmail = (json, name) => {
            const row = json.employees.find(e => e.name === name);
            return row ? row.email : null;
          }
    
    Login or Signup to reply.
  3. In PHP you can do something like this.

    $json = '{"employees":[  
        {"name":"Shyam", "email":"[email protected]", "job":"police"},  
        {"name":"Bob", "email":"[email protected]", "job":"athelic"},  
        {"name":"Jai", "email":"[email protected]", "job":"king"}  
    ]} ';
    
    $jsonArray = json_decode($json, true);
    $emails = [];
    
    foreach ($jsonArray['employees'] as $item){
        if ($item['name'] == "Shyam") {
            $emails[] = $item['email'];
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search