Current Location: Home> Latest Articles> How to Add Key-Value Pairs to JSON in PHP

How to Add Key-Value Pairs to JSON in PHP

gitbox 2025-08-04

What is JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format. It is easy for humans to read and write, and easy for machines to parse and generate. JSON is widely used for data communication between different systems, especially between the frontend and backend in web development.

Basic Structure of JSON

JSON supports various data types including strings, numbers, booleans, null, as well as complex types such as objects (key-value pairs) and arrays. PHP can handle all of these structures conveniently.

How to Work with JSON in PHP

PHP provides built-in functions to encode and decode JSON data. The most commonly used ones are json_encode() and json_decode(), which allow converting PHP arrays or objects into JSON strings and vice versa.

Using json_encode to Generate a JSON String

Here is an example of converting a PHP array into a JSON string:


  $person = array('name' => 'Tom', 'age' => 20, 'isMarried' => false);
  $jsonStr = json_encode($person);
  echo $jsonStr;

The output will be the following JSON string:

{"name":"Tom","age":20,"isMarried":false}

Using json_decode to Parse a JSON String

The example below demonstrates how to convert a JSON string back into a PHP array:


  $jsonStr = '{"name":"Tom","age":20,"isMarried":false}';
  $person = json_decode($jsonStr, true); // true returns an associative array
  print_r($person);

The output array will be:

Array ( [name] => Tom [age] => 20 [isMarried] => )

How to Add Key-Value Pairs to JSON in PHP

To add a new value to existing JSON data in PHP, first decode the JSON string into a PHP array, modify the array, and then re-encode it back into a JSON string.


  // Original JSON string
  $jsonStr = '{"name":"Tom","age":20,"isMarried":false}';

  // Decode to PHP array
  $person = json_decode($jsonStr, true);

  // Add a new key-value pair
  $person['email'] = '[email protected]';

  // Re-encode to JSON string
  $newJsonStr = json_encode($person);
  echo $newJsonStr;

The output will be:

{"name":"Tom","age":20,"isMarried":false,"email":"[email protected]"}

Conclusion

By using json_decode() to convert a JSON string into an array, modifying the array, and then using json_encode() to convert it back, PHP developers can easily manipulate JSON data. This is especially useful in web development where data frequently needs to be exchanged between frontend and backend, improving development speed and code maintainability.