ajayvohra2005/hack-jmespath

JMESPath search in Hacklang

v1.0.1 2021-09-20 20:30 UTC

This package is auto-updated.

Last update: 2022-05-20 22:00:06 UTC


README

Overview

This Hack package allows one to search and extract elements from a JSON document using JMESPath query language.

Requirements

HHVM 4.123 and above.

Installation

  • Git clone this repository

  • Install composer

  • In the root directory of this repository, run the command

      composer install
    

To use this package,

    composer require ajayvohra2005/hack-jmespath

Running Tests

After installation, run the following command in the root directory of this repository:

    ./vendor/bin/hacktest tests/

Example Code

Below is a an example for searching a json document using a JMESPath query expression:

use namespace HackJmesPath;

<<__EntryPoint>>
function jmespath_example(): void {
  require_once(__DIR__.'/../vendor/autoload.hack');
  \Facebook\AutoloadMap\initialize();

    $json = '{
        "people": [
        {
            "name": "Jeff",
            "age": 33,
            "state": {"name": "up"}
        },
        {
            "name": "Bill",
            "age": 51,
            "state": {"name": "down"}
        },
        {
            "name": "Luna",
            "age": 42,
            "state": {"name": "up"}
        }
        ]
    }';

    $espression = "sort_by(people, &age)[].name";
    $result = HackJmesPath\jmespath_search($espression, $json);

    var_dump($result);
}

which produces the following expected output:

vec(3) {
  string(4) "Jeff"
  string(4) "Luna"
  string(4) "Bill"
}

More Examples

See tests/TreeInterpreterTest.hack for a complete list of test cases, and more examples.

Decoding JSON Data Types

JSON 'object' type must be represented by a Hack dict. The stdClass is not supported for a JSON 'object'. This means if you use the Hack built-in function json_decode(), the second argument in the function call must be true so that associative arrays are used.

JMESPath Query Language

Please refer to the in-depth JMESPath Tutorial to learn about JMESPath json query language.

Acknowledgements

The JMESPath package for PHP in-part inspired this code. See individual source files for copyright acknowledgement.