Category: Utility Classes

Q: How to Hash::extract value from JSON data (utility class)

Accroding to Hash::extract() method, to retrieve data from arrays or object implementing with "Hash Path Syntax". For example:

// Common Usage:
$users = [
    ['id' => 1, 'name' => 'mark'],
    ['id' => 2, 'name' => 'jane'],
    ['id' => 3, 'name' => 'sally'],
    ['id' => 4, 'name' => 'jose'],
];
$results = Hash::extract($users, '{n}.id');
// $results equals:
// [1,2,3,4];

Now if I have a JSON string (from NoSQL database), and I want to extract name column only and foreach to a new array for example through Hash::extract. 

[
  {
    "_id": "57ef9bec6f45e3f450d49602",
    "index": 0,
    "guid": "e86bc6e5-8cdb-48bd-a22f-aad29d88f708",
    "isActive": false,
    "balance": "$3,641.35",
    "picture": "http://placehold.it/32x32",
    "age": 34,
    "eyeColor": "blue",
    "name": "Walters Mcclure",
    "gender": "male",
    "company": "TALKALOT",
    "email": "waltersmcclure@talkalot.com",
    "phone": "+1 (943) 595-2258",
    "address": "665 Roder Avenue, Zortman, Missouri, 9528",
    "about": "Duis officia reprehenderit qui pariatur in cillum proident voluptate incididunt sunt veniam. Nostrud consectetur cillum ad consequat eu veniam est sint est aute. Anim sit veniam ea mollit aliquip ex aliquip amet commodo ipsum. Sint exercitation elit nisi aute aliqua sit nisi consectetur enim cupidatat eu. Officia non ea eu non ad.\r\n",
    "registered": "2016-05-24T04:49:42 -08:00",
    "latitude": 1.119457,
    "longitude": 62.228208,
    "tags": [
      "magna",
      "sunt",
      "quis",
      "nisi",
      "occaecat",
      "eu",
      "sunt"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Reyes Wilkinson"
      },
      {
        "id": 1,
        "name": "Leta Webster"
      },
      {
        "id": 2,
        "name": "Cecile Lester"
      }
    ],
    "greeting": "Hello, Walters Mcclure! You have 2 unread messages.",
    "favoriteFruit": "banana"
  },
  {
    "_id": "57ef9bec49fffaf91342bb10",
    "index": 1,
    "guid": "e048f058-f2ab-499e-bd46-999e81db30cb",
    "isActive": true,
    "balance": "$3,312.01",
    "picture": "http://placehold.it/32x32",
    "age": 30,
    "eyeColor": "blue",
    "name": "Lorrie Hodges",
    "gender": "female",
    "company": "APEXIA",
    "email": "lorriehodges@apexia.com",
    "phone": "+1 (842) 456-3165",
    "address": "284 Sumpter Street, Gerton, Minnesota, 4740",
    "about": "Et officia deserunt culpa sint nulla id consectetur ut. Amet culpa voluptate ad Lorem aliquip eiusmod proident. Excepteur dolor proident proident proident commodo duis amet consectetur labore eiusmod aliqua nostrud magna nisi. Et qui occaecat velit ex. Ipsum duis laborum velit do elit ullamco fugiat minim exercitation ea eiusmod.\r\n",
    "registered": "2014-12-02T08:16:01 -08:00",
    "latitude": -50.377281,
    "longitude": -26.679552,
    "tags": [
      "cupidatat",
      "et",
      "esse",
      "laborum",
      "eu",
      "occaecat",
      "commodo"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Carmella Parks"
      },
      {
        "id": 1,
        "name": "Nona Perkins"
      },
      {
        "id": 2,
        "name": "Geneva Branch"
      }
    ],
    "greeting": "Hello, Lorrie Hodges! You have 6 unread messages.",
    "favoriteFruit": "banana"
  },
  {
    "_id": "57ef9bec2b1b9d8b58c7e91f",
    "index": 2,
    "guid": "fc01837b-6900-465c-bc25-374726a51a6d",
    "isActive": true,
    "balance": "$2,833.98",
    "picture": "http://placehold.it/32x32",
    "age": 30,
    "eyeColor": "blue",
    "name": "Macdonald Hahn",
    "gender": "male",
    "company": "EVENTIX",
    "email": "macdonaldhahn@eventix.com",
    "phone": "+1 (952) 408-3633",
    "address": "300 Barbey Street, Walker, Tennessee, 9628",
    "about": "Velit tempor adipisicing elit proident est commodo magna adipisicing adipisicing est sit exercitation proident pariatur. Adipisicing deserunt nostrud minim et voluptate. Elit velit cupidatat commodo officia ipsum aute quis amet. Tempor ipsum fugiat dolor qui aliquip culpa aute sint sunt occaecat. Nostrud amet Lorem ex dolore duis veniam quis nisi Lorem officia duis. Proident aute reprehenderit tempor ea magna deserunt ut Lorem magna in tempor est dolor commodo.\r\n",
    "registered": "2014-05-09T12:17:13 -08:00",
    "latitude": -42.151624,
    "longitude": -141.516372,
    "tags": [
      "sint",
      "ullamco",
      "deserunt",
      "et",
      "amet",
      "aute",
      "ullamco"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Koch Boone"
      },
      {
        "id": 1,
        "name": "Helene Beck"
      },
      {
        "id": 2,
        "name": "Decker Serrano"
      }
    ],
    "greeting": "Hello, Macdonald Hahn! You have 8 unread messages.",
    "favoriteFruit": "strawberry"
  },
  {
    "_id": "57ef9bec13b81c02cd710184",
    "index": 3,
    "guid": "40994f7d-3594-4965-af16-6249f3165b51",
    "isActive": true,
    "balance": "$1,115.06",
    "picture": "http://placehold.it/32x32",
    "age": 26,
    "eyeColor": "brown",
    "name": "Adkins Jarvis",
    "gender": "male",
    "company": "MENBRAIN",
    "email": "adkinsjarvis@menbrain.com",
    "phone": "+1 (915) 476-3084",
    "address": "447 Strickland Avenue, Falmouth, Rhode Island, 244",
    "about": "Magna eu aliqua ullamco Lorem aliqua culpa. Tempor ea in laboris elit. Mollit adipisicing elit esse cillum pariatur quis anim anim deserunt. Enim Lorem non proident fugiat.\r\n",
    "registered": "2016-01-31T08:41:04 -08:00",
    "latitude": -79.612535,
    "longitude": -135.354052,
    "tags": [
      "aliquip",
      "officia",
      "sunt",
      "aliqua",
      "quis",
      "mollit",
      "incididunt"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Jeanne Osborn"
      },
      {
        "id": 1,
        "name": "Odom Day"
      },
      {
        "id": 2,
        "name": "Dodson Spence"
      }
    ],
    "greeting": "Hello, Adkins Jarvis! You have 7 unread messages.",
    "favoriteFruit": "apple"
  },
  {
    "_id": "57ef9becb6c96804ccf5b786",
    "index": 4,
    "guid": "26b5ee02-5359-4841-97d6-4369928fa67c",
    "isActive": true,
    "balance": "$3,769.11",
    "picture": "http://placehold.it/32x32",
    "age": 33,
    "eyeColor": "green",
    "name": "Rhoda Gilliam",
    "gender": "female",
    "company": "STEELFAB",
    "email": "rhodagilliam@steelfab.com",
    "phone": "+1 (975) 404-2976",
    "address": "849 Boerum Place, Reno, South Dakota, 8987",
    "about": "Laborum adipisicing ipsum dolore Lorem id culpa esse tempor Lorem minim deserunt ullamco. Nisi ut elit esse eiusmod mollit amet consequat commodo in nisi. Officia labore do id ut ea. Pariatur ipsum Lorem occaecat exercitation laborum Lorem ad. Nostrud consequat proident elit sint ex sit irure ullamco elit labore.\r\n",
    "registered": "2014-07-08T08:13:03 -08:00",
    "latitude": -56.934267,
    "longitude": 94.492062,
    "tags": [
      "exercitation",
      "cillum",
      "dolore",
      "id",
      "duis",
      "laboris",
      "ea"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Clemons Whitney"
      },
      {
        "id": 1,
        "name": "Guadalupe Acevedo"
      },
      {
        "id": 2,
        "name": "Concetta Myers"
      }
    ],
    "greeting": "Hello, Rhoda Gilliam! You have 4 unread messages.",
    "favoriteFruit": "banana"
  }
]

Am I possible to do that, or should I write my own class to do so?

The expect output should be:

debug($result);
// ['Walters Mcclure', 'Lorrie Hodges', 'Macdonald Hahn', 'Adkins Jarvis', 'Rhoda Gilliam']

Anyone? Thanks

hash extract json
1 Answers

Version: 3

user
usabob

2

You have to do json_decode() first to convert JSON string to PHP array.

<?php
namespace App\Controller;

use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;

use Cake\Utility\Hash;

class ExampleController extends AppController {

    public function test() {

        $json = '[{"_id":"57ef9bec6f45e3f450d49602","index":0,"guid":"e86bc6e5-8cdb-48bd-a22f-aad29d88f708","isActive":false,"balance":"$3,641.35","picture":"http://placehold.it/32x32","age":34,"eyeColor":"blue","name":"Walters Mcclure","gender":"male","company":"TALKALOT","email":"waltersmcclure@talkalot.com","phone":"+1 (943) 595-2258","address":"665 Roder Avenue, Zortman, Missouri, 9528","about":"Duis officia reprehenderit qui pariatur in cillum proident voluptate incididunt sunt veniam. Nostrud consectetur cillum ad consequat eu veniam est sint est aute. Anim sit veniam ea mollit aliquip ex aliquip amet commodo ipsum. Sint exercitation elit nisi aute aliqua sit nisi consectetur enim cupidatat eu. Officia non ea eu non ad.\r\n","registered":"2016-05-24T04:49:42 -08:00","latitude":1.119457,"longitude":62.228208,"tags":["magna","sunt","quis","nisi","occaecat","eu","sunt"],"friends":[{"id":0,"name":"Reyes Wilkinson"},{"id":1,"name":"Leta Webster"},{"id":2,"name":"Cecile Lester"}],"greeting":"Hello, Walters Mcclure! You have 2 unread messages.","favoriteFruit":"banana"},{"_id":"57ef9bec49fffaf91342bb10","index":1,"guid":"e048f058-f2ab-499e-bd46-999e81db30cb","isActive":true,"balance":"$3,312.01","picture":"http://placehold.it/32x32","age":30,"eyeColor":"blue","name":"Lorrie Hodges","gender":"female","company":"APEXIA","email":"lorriehodges@apexia.com","phone":"+1 (842) 456-3165","address":"284 Sumpter Street, Gerton, Minnesota, 4740","about":"Et officia deserunt culpa sint nulla id consectetur ut. Amet culpa voluptate ad Lorem aliquip eiusmod proident. Excepteur dolor proident proident proident commodo duis amet consectetur labore eiusmod aliqua nostrud magna nisi. Et qui occaecat velit ex. Ipsum duis laborum velit do elit ullamco fugiat minim exercitation ea eiusmod.\r\n","registered":"2014-12-02T08:16:01 -08:00","latitude":-50.377281,"longitude":-26.679552,"tags":["cupidatat","et","esse","laborum","eu","occaecat","commodo"],"friends":[{"id":0,"name":"Carmella Parks"},{"id":1,"name":"Nona Perkins"},{"id":2,"name":"Geneva Branch"}],"greeting":"Hello, Lorrie Hodges! You have 6 unread messages.","favoriteFruit":"banana"},{"_id":"57ef9bec2b1b9d8b58c7e91f","index":2,"guid":"fc01837b-6900-465c-bc25-374726a51a6d","isActive":true,"balance":"$2,833.98","picture":"http://placehold.it/32x32","age":30,"eyeColor":"blue","name":"Macdonald Hahn","gender":"male","company":"EVENTIX","email":"macdonaldhahn@eventix.com","phone":"+1 (952) 408-3633","address":"300 Barbey Street, Walker, Tennessee, 9628","about":"Velit tempor adipisicing elit proident est commodo magna adipisicing adipisicing est sit exercitation proident pariatur. Adipisicing deserunt nostrud minim et voluptate. Elit velit cupidatat commodo officia ipsum aute quis amet. Tempor ipsum fugiat dolor qui aliquip culpa aute sint sunt occaecat. Nostrud amet Lorem ex dolore duis veniam quis nisi Lorem officia duis. Proident aute reprehenderit tempor ea magna deserunt ut Lorem magna in tempor est dolor commodo.\r\n","registered":"2014-05-09T12:17:13 -08:00","latitude":-42.151624,"longitude":-141.516372,"tags":["sint","ullamco","deserunt","et","amet","aute","ullamco"],"friends":[{"id":0,"name":"Koch Boone"},{"id":1,"name":"Helene Beck"},{"id":2,"name":"Decker Serrano"}],"greeting":"Hello, Macdonald Hahn! You have 8 unread messages.","favoriteFruit":"strawberry"},{"_id":"57ef9bec13b81c02cd710184","index":3,"guid":"40994f7d-3594-4965-af16-6249f3165b51","isActive":true,"balance":"$1,115.06","picture":"http://placehold.it/32x32","age":26,"eyeColor":"brown","name":"Adkins Jarvis","gender":"male","company":"MENBRAIN","email":"adkinsjarvis@menbrain.com","phone":"+1 (915) 476-3084","address":"447 Strickland Avenue, Falmouth, Rhode Island, 244","about":"Magna eu aliqua ullamco Lorem aliqua culpa. Tempor ea in laboris elit. Mollit adipisicing elit esse cillum pariatur quis anim anim deserunt. Enim Lorem non proident fugiat.\r\n","registered":"2016-01-31T08:41:04 -08:00","latitude":-79.612535,"longitude":-135.354052,"tags":["aliquip","officia","sunt","aliqua","quis","mollit","incididunt"],"friends":[{"id":0,"name":"Jeanne Osborn"},{"id":1,"name":"Odom Day"},{"id":2,"name":"Dodson Spence"}],"greeting":"Hello, Adkins Jarvis! You have 7 unread messages.","favoriteFruit":"apple"},{"_id":"57ef9becb6c96804ccf5b786","index":4,"guid":"26b5ee02-5359-4841-97d6-4369928fa67c","isActive":true,"balance":"$3,769.11","picture":"http://placehold.it/32x32","age":33,"eyeColor":"green","name":"Rhoda Gilliam","gender":"female","company":"STEELFAB","email":"rhodagilliam@steelfab.com","phone":"+1 (975) 404-2976","address":"849 Boerum Place, Reno, South Dakota, 8987","about":"Laborum adipisicing ipsum dolore Lorem id culpa esse tempor Lorem minim deserunt ullamco. Nisi ut elit esse eiusmod mollit amet consequat commodo in nisi. Officia labore do id ut ea. Pariatur ipsum Lorem occaecat exercitation laborum Lorem ad. Nostrud consequat proident elit sint ex sit irure ullamco elit labore.\r\n","registered":"2014-07-08T08:13:03 -08:00","latitude":-56.934267,"longitude":94.492062,"tags":["exercitation","cillum","dolore","id","duis","laboris","ea"],"friends":[{"id":0,"name":"Clemons Whitney"},{"id":1,"name":"Guadalupe Acevedo"},{"id":2,"name":"Concetta Myers"}],"greeting":"Hello, Rhoda Gilliam! You have 4 unread messages.","favoriteFruit":"banana"}]';

        $data = json_decode($json, true); //convert JSON to array
        $output = Hash::extract($data, '{n}.name'); //extract name column
        debug($output);

        $this->autoRender = false;
    }
}

output:

[
	(int) 0 => 'Walters Mcclure',
	(int) 1 => 'Lorrie Hodges',
	(int) 2 => 'Macdonald Hahn',
	(int) 3 => 'Adkins Jarvis',
	(int) 4 => 'Rhoda Gilliam'
]

Created: 1 Oct '16

Last Reply: 1 Oct '16

Replies: 1

Views: 512

Votes: 1

Welcome to Aero Coding!

Aero Coding is a CakePHP-focused Q&A community for professional and enthusiast cake bakers. It's built and run by you as part of the community.


Join Now Tour

Download Cakephp

Start baking your own CakePHP application!


Cakephp All Versions