I need to decode the JSON string variable to an associative array. The problem I faced was that the key and value of the JSON string don't have quotes. So I want to add the quotes to each key and value. The JSON string that I have:
$incorrectJsonString = "{
id: uepwhfkj,
name: sthfor.test,
product: SIDO-EOSJGF-DOE_IEO
}";
The output that I want:
$correctJsonString = '{
"id": "uepwhfkj",
"name": "sthfor.test",
"product": "SIDO-EOSJGF-DOE_IEO"
}';
At least I need to decode this JSON string :
json_decode($correctJsonString, TRUE);
CodePudding user response:
The is no such thing as a 'incorrect JSON string'. A string is either valid JSON or not.
Here is a quick solution, but I would not recommend to try to transform such a string into valid JSON, there are too many problems which can arise.
The solution is to fix the code which provides what you call 'incorrect JSON string'.
$text = '{
id: uepwhfkj,
name: sthfor.test,
product: SIDO-EOSJGF-DOE_IEO
}';
$lines = preg_split("/\r\n|\n|\r/", $text);
$members = array_slice($lines, 1, count($lines) - 2);
foreach ($members as &$line) {
$indexOfFirstColon = strrpos($line, ':');
$member = trim(substr($line, 0, $indexOfFirstColon));
$element = rtrim(trim(substr($line, $indexOfFirstColon 1)), ',');
$line = " \"$member\" : \"$element\"";
}
unset($line);
$json = '{' . "\n" . implode(",\n", $members) . "\n" . '}';
print_r($json);
CodePudding user response:
You can the following regex with substitution
(\w ):\s(.*?)(,|$)
See regex demo and PHP example
CodePudding user response:
You can correct string using preg_replace:
<?php
$incorrectJsonString = "{
id: uepwhfkj,
name: sthfor.test,
product: SIDO-EOSJGF-DOE_IEO
}";
$correctJsonString = preg_replace('/(\S ):\s*([^,\n] )(,?\n?)/m', '"$1": "$2"$3', $incorrectJsonString);
// echo $correctJsonString;
var_dump(json_decode($correctJsonString, true));