I’d like to increment a JSON object with a new given one but I can’t do it. I have the following JSON:
{ "field_name":{ "type":"text", "visual_name":"Field Name", "required": true } }
The user will create more fields and I’d like to insert in the original JSON the new field that comes in this format:
"field_name2":{ "type":"select", "visual_name":"Field Name 2", "required": true, "options":{"opt1":"yes","opt2":"no"} }
Advertisement
Answer
Looks like you’re trying to add new elements to the root JSON object, in which case you simply need to:
- Decode the JSON objects into PHP arrays.
- Merge the arrays into one.
- Encode the merged array back into JSON.
$field1 = '{"field_name":{"type":"text", "visual_name":"Field Name", "required":true}}'; $field2 = '{"field_name2":{"type":"select", "visual_name":"Field Name 2", "required":true, "options":{"opt1":"yes", "opt2":"no"}}}'; $arr = array_merge(json_decode($json1, true), json_decode($json2, true)); $json = json_encode($arr);
The final $json
object will be:
{ "field_name": { "type": "text", "visual_name": "Field Name", "required": true }, "field_name2": { "type": "select", "visual_name": "Field Name 2", "required": true, "options": { "opt1": "yes", "opt2": "no" } } }
If you want to add the fields into a JSON array, rather than an object, you can do this instead:
$arr = [json_decode($json1, true), json_decode($json2, true)];
Which results in:
[ { "field_name": { "type": "text", "visual_name": "Field Name", "required": true } }, { "field_name2": { "type": "select", "visual_name": "Field Name 2", "required": true, "options": { "opt1": "yes", "opt2": "no" } } } ]
Note
If you try to add your original second field as you have given it in your question, it won’t work because it’s not a fully formatted JSON string. You must ensure it has the outer pair of curly braces.
Incorrect:
"field_name2":{"type":"select", "visual_name": ...}
Correct:
{"field_name2":{"type":"select", "visual_name": ...}}