Skip to content
Advertisement

Json_encode returns json cells as string

I’ve got a database structure like this. I’m willing to get row as a json object for Json.net.

My php code is this

JavaScript

I’m getting json as this.

JavaScript

As you can see, subscriptions value is string. I need it to be array as it seems.

JavaScript

Is there any way to achieve this. ?

Thanks a lot !

Advertisement

Answer

The way you’re retrieving that data is giving you the JSON value as a string. Storing it as JSON in the database is a good idea if it’s actually JSON data, but the mysqli driver will not automatically de-serialize it for you. If you want that sort of behaviour you’ll need to use an ORM.

When you’re having trouble with double encoding, check with var_dump to see what you’re actually working with. That would reveal the subscriptions key contains a JSON string, not an array as expected.

What you’ll have to do is manually de-serialize it prior to JSON encoding:

JavaScript

You will need to do this for any and all JSON encoded fields your results might have.

This way you’re JSON encoding a proper PHP data structure and not one that’s part PHP and part JSON string.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement