简体   繁体   中英

Find all numeric values in JSON and replace them enclosed in quotes

[{
  "SomeValue1": 16237351025487570926,
  "SomeValue2": "value2",
  "SomeValue3": "value3"
 }, {
  "SomeValue1": 16237351025487570926,
  "SomeValue2": "value2",
  "SomeValue3": "value3"
}]

I need to search and replace SomeValue1 with same value but wrapped in quotes (shown bellow).

[{
  "SomeValue1": "16237351025487570926",
  "SomeValue2": "value2",
  "SomeValue3": "value3"
 }, {
  "SomeValue1": "16237351025487570926",
  "SomeValue2": "value2",
  "SomeValue3": "value3"
}]

I need to have php regex (JSON_BIGINT_AS_STRING is somethink else in this case) .

Thanks !

JSON_BIGINT_AS_STRING is actually not something else:

$json = '[{
  "SomeValue1": 16237351025487570926
 }, {
  "SomeValue1": 16237351025487570926
}]';

var_dump(json_decode($json));
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));

Outputs:

array(2) {
  [0]=> object(stdClass)#1 (1) {
    ["SomeValue1"] => float(1.6237351025488E+19)
  }
  [1]=> object(stdClass)#2 (1) {
    ["SomeValue1"] => float(1.6237351025488E+19)
  }
}

array(2) {
  [0]=> object(stdClass)#2 (1) {
    ["SomeValue1"] => string(20) "16237351025487570926"
  }
  [1]=> object(stdClass)#1 (1) {
    ["SomeValue1"] => string(20) "16237351025487570926"
  }
}

So basically, you can just do:

echo json_encode(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));

This only works for a large enough integer that it is actually a float, if you want to convert every integer just loop over the array:

foreach($arr = json_decode($json, true, 512, JSON_BIGINT_AS_STRING) as $key => $value){
  foreach($value as $k => $v){
    if(gettype($v) == 'integer'){
      $arr[$key][$k] = (string) $v;
    }
  }
}

echo json_encode($arr);

You might use something like this

\s(\d+), 

and then replace with

"$1"

Explanation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM