1

json_decode('["foo","bar"]', true), this works, but this return NULL, json_decode("['foo','bar']", true). The json_last_error() outputs 4, JSON_ERROR_SYNTAX.

I've checked some answers from following questions;

json_decode() returns null issues

PHP json_decode() returns NULL with valid JSON?

json_decode returns NULL after webservice call

and tried following solutions but no success;

json_decode(str_replace('"', '"', "['foo','bar']"), true)

json_decode(stripslashes(str_replace('\"', '"', "['foo','bar']")), true)

json_decode(stripslashes("['foo','bar']"), true)

json_decode(utf8_encode("['foo','bar']"), true)

I don't think it has to do with UTF-8 bom. Is it a PHP bug? Or how do I do turn "['foo','bar']" into '["foo","bar"]' as a workaround?

Community
  • 1
  • 1
sulaiman sudirman
  • 1,826
  • 1
  • 24
  • 32
  • 1
    The string the the function `json_decode` takes as a parameter needs to be valid JSON. `{"a":1,"b":2,"c":3,"d":4,"e":5}` this is valid JSON. You are just passing in an array wrapped in quotes. – sidneydobber Jan 14 '16 at 15:03

2 Answers2

0

You are not providing valid json to a function. If u using javascript array

    ["foo","bar"]
You should use JSON.stringify to make JSON actually on js side.
Bisk
  • 36
  • 4
0

JSON strings are quoted with double quotes ". Single quotes ' (which are common in PHP) are not valid JSON. No discussion. Thus, the input ['foo','bar'] is not valid json and json_decode correctly refuses to parse it.

Also see ECMA-404, which defines the JSON format:

A string is a sequence of Unicode code points wrapped with quotation marks (U+0022).1

If you're looking for something to transform your JSON-ish string (where does it come from? Fix the source of the invalid JSON, preferably) into valid JSON; str_replace('\'', '"', $jsonInput) should work in simple cases.


1(U+0022 is the double quote ")

helmbert
  • 35,797
  • 13
  • 82
  • 95