change json key name [ json generated using json_e

2020-02-06 07:14发布

I am generating json from an array using json_encode(), it's working properly, but it uses the key:value from the array, as usual. but I want to change the name of the key only in the json output.. is it possible to do it ? 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)

标签: php json
4条回答
我命由我不由天
2楼-- · 2020-02-06 07:43

Only if you rewrite 'm yourself. You could 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 if that's what you were aiming for.

查看更多
时光不老,我们不散
3楼-- · 2020-02-06 07:43

This may be a short answer:

foreach ($list as $key => $val) {
    $newList[$key] = [
        'foo'   =>  $val['a'],
        'something' =>    $val['b'],
        'bar' => $val['c'],
        'foo' => $val['d'],
        'baz' => $val['e'],
    ];
}
查看更多
Luminary・发光体
4楼-- · 2020-02-06 08:00

You can always json_decode it and then re-encode it. But it's going to be easiest if you simply prepare your keys before you encode it.

查看更多
够拽才男人
5楼-- · 2020-02-06 08:04

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

There is a code for your case.

$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);
查看更多
登录 后发表回答