Almas
Almas

Reputation: 319

How to json string convert to php array?

I am trying to get php array from json string

$testData = "{
        'data' :[{
            'id' : '201120121',
            'bsid' : '200',
            'bspaymentcode' : '12',
            'service' : 'bed set',
            'cost' : '2000',
            'date_begin' : '12.12.14',
            'date_end' : '01.01.15' 
        } , 
        {
            'id' : '20133231',
            'bsid' : '220',
            'bspaymentcode' : '22',
            'service' : 'sport center',
            'cost' : '2000',
            'date_begin' : '12.12.14',
            'date_end' : '01.01.15' 
        }]
    }";

var_dump(json_decode($testData,true));exit;

But i have NULL. Any ideas?

Upvotes: 1

Views: 63

Answers (4)

Cpu Nerd
Cpu Nerd

Reputation: 312

Yea it looks like everything is correct except your JSON syntax (you need double quotes not single quotes). Here is a great site to check your JSON string/object and it tells you what the issue is:

http://jsonformatter.curiousconcept.com/

Upvotes: 0

Aaron Chen
Aaron Chen

Reputation: 140

Swap double quote(") with single quote(') will solve the issue.

Upvotes: 0

lighter
lighter

Reputation: 2806

If you can't change the variable's single quotes (your data content is from another variable), I think you can use str_replace, this is code for you

$testData = "{
        'data' :[{
            'id' : '201120121',
            'bsid' : '200',
            'bspaymentcode' : '12',
            'service' : 'bed set',
            'cost' : '2000',
            'date_begin' : '12.12.14',
            'date_end' : '01.01.15' 
        } , 
        {
            'id' : '20133231',
            'bsid' : '220',
            'bspaymentcode' : '22',
            'service' : 'sport center',
            'cost' : '2000',
            'date_begin' : '12.12.14',
            'date_end' : '01.01.15' 
        }]
    }";
$testData = str_replace("'", '"', $testData);

var_dump(json_decode($testData,true));exit;

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

JSON uses double quotes for strings. Your string uses single quotes, therefore it's not valid JSON, and json_decode returns NULL.

Upvotes: 6

Related Questions