JSON Notation for PHP 7.0

Posted by Stuart Herbert on July 9th, 2016 in Uncategorized.

tldr; I’ve been experimenting with the PHP interpreter, and I made a thing …

JSON is by far the most common API request format. I design, build, and fix API servers for a living. I write a lot of API tests as a result.

I often find myself wishing that I could write JSON directly in PHP code like this:

$payload = {
  "hello": {
     "fish": $fishType
  }
};

This would save me a lot of time when I’m copying examples from API documentation or JIRA tickets into my test suites.

You’ll find a patch that adds this to PHP 7.0 here: diff against PHP-7.0 tracking branch.

Some caveats: I’m no expert on the internals of PHP, and this patch is very naive. It probably breaks things in ways that I’m not aware of. It passes the PHP test suite locally, but that doesn’t mean you should be trying this in production.

Here’s some examples of what it allows you to do:

<?php

// this is an array syntax that PHP
// already supports
$a1 = [
  "hello" => "world"
];
var_dump($a1);

// and this should be an array too now
$a2 = [
  "hello": "world"
];
var_dump($a2);

// this is forced to be an array
$a3 = (array){
  "hello": "world"
};
var_dump($a3);

// and this should be an object
//
// you can still use array assignment inside
$a4 = {
  "hello": "world",
  "goodbye" => "everyone"
};
var_dump($a4);

// this should be an object inside an object
$a5 = {
  "hello": {
     "fish": "trout"
  }
};
var_dump($a5);

// create an array of objects
$a6 = [
    {
        "hello": "world"
    },
    {
        "goodbye" => "everyone"
    }
];
var_dump($a6);

// this is an object that contains an array
$a7 = {
    "hello": [
        "world",
        "trout"
    ]
};
var_dump($a7);

// we can still cast nested arrays to objects
$a8 = {
    "hello": (object)[
        "world",
        "trout"
    ]
};
var_dump($a8);

// we can pass data objects as arguments too
function provide($arg1) {
    return $arg1;
}
var_dump(provide({"hello": "world"}));

// we can define and return data objects
// without having to assign to a var first
function returnObject() {
    return { "hello": "world" };
}

Let me know if you’d also find this useful. If there’s enough interest, I’ll see if I can convince someone who is involved in the world of PHP.internals to help me get this turned into an RFC.

Be the first to leave a comment »

This Month

July 2016
M T W T F S S
« Feb    
 123
45678910
11121314151617
18192021222324
25262728293031