How to decode_json string without quotes in PHP?

Issue

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);

Solution

You can use the following regex with substitution

(\w+):\s(.*?)(,|$)

See regex demo and PHP example

Answered By – Artyom Vancyan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published