1

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?

1
  • 1
    Your json is invalid. It should use double quotes not single quotes for values. Commented Nov 24, 2014 at 3:33

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

0

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

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.