Viewed   329 times

Sample code:

<?php

$json = "['foo', 'bar']";

var_dump( json_decode($json) );

It works with PHP 5.5.3 but it fails for lower PHP's versions

It works on my machine with PHP 5.5.3 but it fails everywhere else.

I know it is incorrect JSON but my webservice gives me JSON with ' symbols together with "

['foo', "bar", {'test': "crazy "markup""}]

Sandbox

How to parse JSON data with apostrophes in PHP 5.3? Obviously original JSON I want to parse is more complex.

(I can't upgrade my PHP on production server neither get proper JSON from webservice)

 Answers

4

Here's an alternative solution to this problem:

function fixJSON($json) {
    $regex = <<<'REGEX'
~
    "[^"\]*(?:\.|[^"\]*)*"
    (*SKIP)(*F)
  | '([^'\]*(?:\.|[^'\]*)*)'
~x
REGEX;

    return preg_replace_callback($regex, function($matches) {
        return '"' . preg_replace('~\\.(*SKIP)(*F)|"~', '\"', $matches[1]) . '"';
    }, $json);
}

This approach is more robust than h2ooooooo's function in two respects:

  • It preserves double quotes occurring in a single quoted string, by applying additional escaping to them. h2o's variant will replace them with double quotes instead, thus changing the value of the string.
  • It will properly handle escaped double quotes ", for which h2o's version seems to go into an infinite loop.

Test:

$brokenJSON = <<<'JSON'
['foo', {"bar": "hel'lo", "foo": 'ba"r ba"z', "baz": "wor"ld ' test"}]
JSON;

$fixedJSON = fixJSON($brokenJSON);
$decoded = json_decode($fixedJSON);

var_dump($fixedJSON);
print_r($decoded);

Output:

string(74) "["foo", {"bar": "hel'lo", "foo": "ba"r ba"z", "baz": "wor"ld ' test"}]"
Array
(
    [0] => foo
    [1] => stdClass Object
        (
            [bar] => hel'lo
            [foo] => ba"r ba"z
            [baz] => wor"ld ' test
        )
)
Tuesday, September 27, 2022
5

Try something like this:

//initialize array
$myArray = array();

//set up the nested associative arrays using literal array notation
$firstArray = array("id" => 1, "data" => 45);
$secondArray = array("id" => 3, "data" => 54);

//push items onto main array with bracket notation (this will result in numbered indexes)
$myArray[] = $firstArray;
$myArray[] = $secondArray;

//convert to json
$json = json_encode($myArray);
Friday, December 23, 2022
5

Here is a complete implementation:

<test-element obj='{"a": 1, "b": 2, "c": 3}'></test-element>

<dom-module id="test-element">
    <template>

        <template is="dom-repeat" items="{{_toArray(obj)}}">
            name: <span>{{item.name}}</span>
            <br> value: <span>{{item.value}}</span>
            <br>
            <hr>
        </template>

    </template>
    <script>
    Polymer({

        properties: {
            obj: Object
        },

        _toArray: function(obj) {
            return Object.keys(obj).map(function(key) {
                return {
                    name: key,
                    value: obj[key]
                };
            });
        }

    });
    </script>

</dom-module>
Sunday, December 11, 2022
 
4

you can use it like this, in JSON format when you evaluate false value it will give you blank, and when you evaluate true it will give you 1.

$str = '[{"clientId":"17295c59-4373-655a-1141-994aec1779dc","channel":"/meta/connect","connectionType":"long-polling","ext":{"fm.ack":false,"fm.sessionId":"22b0bdcf-4a35-62fc-3764-db4caeece44b"},"id":"5"}]';

$arr = json_decode($str,true);

if($arr[0]['ext']['fm.ack'])    // suggested by **mario**
{
    echo "true";    
}
else {
    echo "false";   
}
Thursday, October 6, 2022
3

Have a look at: http://grails.1312388.n4.nabble.com/The-groovy-truth-of-JSONObject-Null-td3661040.html

Ian Roberts mentions a nice trick to make a null check possible:

JSONObject.NULL.metaClass.asBoolean = {-> false} 
Thursday, December 22, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :