Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inline JSON syntax in PHP

Tags:

json

syntax

php

PHP would be a lot cooler if you could write things like this:

$array = [2, 3, 5];

$object = { "name" : "Harry", "age" : 23, "cats" : ["fluffy", "mittens", "whiskers"]};

but, I just spent a lot of time looking for an extension (even an experimental alpha or anything) adding json syntax to PHP but found nothing.

Does anything like this exist?

If not, considering the existence of json_decode() and facebook's XHP, would it be difficult to write an extension to do this?

I have no experience writing PHP extensions, although I did a lot of C in college.

like image 439
Bill Avatar asked Jul 17 '10 23:07

Bill


2 Answers

You could just wrap your datastructure in json_decode and be done with it:

$array = json_decode('[2, 3, 5]');

$object = json_decode('{
                           "name" : "Harry",
                           "age" : 23,
                           "cats" : [
                                        "fluffy", "mittens", "whiskers"
                           ]
                       }');

Yes, it doesn't do typechecking until the statement is executed, and you'll have a bit of a problem handling multiple quotes, but you could always use a HEREDOC for that.

like image 70
bluesmoon Avatar answered Oct 20 '22 06:10

bluesmoon


Different syntax for PHP arrays has been proposed and rejected many times before.

Unfortunate, I know, because I hate the ugly syntax too.

like image 25
quantumSoup Avatar answered Oct 20 '22 05:10

quantumSoup