1

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?

Community
  • 1
  • 1
Nirali Kavar
  • 956
  • 2
  • 8
  • 17

2 Answers2

2

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"}"
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • this code works fine but when i add a new field datetime then this code gives output like this : "2015-06-25 08:"15":"14"" . – Nirali Kavar Jan 26 '16 at 08:58
  • it gives the same output. – Nirali Kavar Jan 26 '16 at 09:40
  • @NiraliKavar, strange ... I suppose that we have worked with different initial strings. What is your initial string? – RomanPerekhrest Jan 26 '16 at 09:43
  • my initial string is like that : {"first_name":"sample","last_name": "lastname","integer" : 100, "float" : 1555.20, "createddate":"2015-06-25 09:57:28"}. – Nirali Kavar Jan 26 '16 at 10:03
  • now json is generate as i want but it gives one more javascript error like that : TypeError: float.toFixed is not a function.. – Nirali Kavar Jan 26 '16 at 10:51
  • Your initial task was "convert integer and float value to string" and `toFixed` isn't a property of non-numeric variable types. Use this approach: `parseFloat(float).toFixed(2)` – RomanPerekhrest Jan 26 '16 at 11:13
1

This sounds like a job for lookaheads and lookbehinds!

$newJson = preg_replace('/("\s*:\s*)(?<!")[\d\.]+(?!")/', '\1"\2"', $json);

You can visualize this here.

(?<!") is a negative lookbehind. It is a "zero length expression" meaning that it doesn't actually match a character; it just prevents a match from occurring if a " was there. (?!") is a negative lookahead, and works the same way, but matches forward instead of backward.

Will
  • 24,082
  • 14
  • 97
  • 108
  • I have one more field for date and its showing me like this, entry_date":"2"015"-"06"-"25" "10": how can i resolve this ? – Nirali Kavar Jan 26 '16 at 07:10
  • i used that new string from your edit but it makes all integer value blank,, Like this [ "integer"":" ] thanks Will :) – Nirali Kavar Jan 26 '16 at 08:38