How To Insert A New Key Value To The Existing JSON- PHP

  1. Home
  2. How to insert a new key value to the existing JSON- PHP
778 votes 2 answers How to insert a new key value to the existing JSON- PHP Get the solution ↓↓↓

I have been searching online for the past 2 hours and couldn't find an answer. I have some data stored in my database in JSON format. I want to add a new key and value to the json data. Example

{ "systemService":"1234", "DATA_PLAN":"SMEF", "amount":"5000" } $message = .$name "" .$post; Copy code

I want to add a new key and value to it."message":$message

to something like this.

{ "systemService":"1234", "DATA_PLAN":"SMEF", "amount":"5000" "message":"mike accountance" } Copy code

How do I go about it in PHP

Undefined asked 2021-11-16 Write your answer 316 votes

Answer

Solution:

Here is an example how you can do it:

Method 1 decoding it to an associative array:

$object = json_decode('{ "systemService":"1234", "DATA_PLAN":"SMEF", "amount":"5000" }', true); $object['message'] = "Your message"; echo json_encode($object); //this will give you the json string with your new property Copy code

Method 2 decoding it to an object:

$object = json_decode('{ "systemService":"1234", "DATA_PLAN":"SMEF", "amount":"5000" }'); $object->message = "Your message"; echo json_encode($object); //this will give you the json string with your new property Copy code Write your answer 684 votes

Answer

Solution:

You could convert the JSON string to object (with PHP

Tag » Add Element Json Php