Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change json key name [ json generated using json_encode ]

Tags:

json

php

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)

like image 347
Vamsi Krishna B Avatar asked May 06 '11 22:05

Vamsi Krishna B


People also ask

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What is json_encode and Json_decode in PHP?

Parsing JSON data in PHP: There are built-in functions in PHP for both encoding and decoding JSON data. These functions are json_encode() and json_decode(). These functions works only with UTF-8 encoded string. Decoding JSON data in PHP: It is very easy to decode JSON data in PHP.

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

How can I get JSON encoded data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.


1 Answers

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.

like image 61
Joshua - Pendo Avatar answered Oct 03 '22 03:10

Joshua - Pendo