Change json key name [json using json_encode]

I am generating json from an array using json_encode() , it works correctly, but it uses the key: value from the array, as usual. but I want to change the key name only in json output .. is it possible to do this? or should I prepare the json key: values ​​myself manually?

Example:

 $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); 

O / p

 {"a":1,"b":2,"c":3,"d":4,"e":5} 

I want.

 {"foo":1,"something":2,"bar":3,"foo":4,"baz":5} 

edit: I cannot edit the original array .. (generated using framweork)

+6
source share
3 answers

Only if you rewrite yourself. You can use:

 $rewriteKeys = array('a' => 'foo', 'b' => 'something', 'c' => 'bar', 'd' => 'foo', 'e' => 'baz'); $newArr = array(); foreach($arr as $key => $value) { $newArr[ $rewriteKeys[ $key ] ] = $value; } echo json_encode($newArr); 

Not sure what you were aiming for.

+4
source

You can always json_decode and then transcode it. But it will be easiest if you just prepare your keys before you encode them.

0
source

There is another option described here . The main idea is to treat JSON as a string, and then use str_replace or preg_replace (str_replace for regexp).

In your case there is a code.

 $mapping_array = array('a' => 'foo', 'b' => 'something', 'c' => 'bar', 'd' => 'foo', 'e' => 'baz'); $tmp_arr = array_map(function($k){ return '/\b'.$k.'\b/u'; }, array_keys($mapping_array)); $new_json = preg_replace($tmp_arr, array_values($mapping_array), $old_json); 
0
source

Source: https://habr.com/ru/post/887487/


All Articles