phpjsonregexpcre

Convert JSON integers and floats to strings


I want to pre-parse a JSON and convert integer and float value to string in the JSON. Also there are some string values in JSON.

For example:

{
    "first_name": "sample",
    "last_name": "lastname",
    "integer" : 100,
    "float" : 1555.20
}

I just use preg_replace() like this from here:

echo preg_replace('/\: *([0-9]+\.?[0-9e+\-]*)/', '"\\1"', $jsonString);

But its not working if I have a string value in my array, it only works if there are only integer and float values in array.

Can anyone help explain why this happens?


Solution

  • Here is solution:

    $str = '{"first_name":"sample",
              "last_name": "lastname",
              "integer" : 100,
              "float" : 1555.20,
              "createddate":"2015-06-25 09:57:28"}';
    
    $result = preg_replace("/(\"\w+\":\s*?)(\d+\.?[^,\}]*\b)/imu",'$1"$2"',$str);
    
    var_dump($result);
    

    // output:
    string(121) "{"first_name":"sample",
    "last_name": "lastname",
    "integer" : 100,
    "float" : 1555.20,
    "createddate":"2015-06-25 09:57:28"}"