Home > Software design >  PHP - How to edit Array Elements from JSON File?
PHP - How to edit Array Elements from JSON File?

Time:04-09

I'm learning more about parsing JSON in PHP, and I encountered a problem editing a certain file.

I wrote a code that makes it possible to edit only the values I want from a JSON file, and for some reason, when I try to edit the value from "IdList", my code replaces that value without the square brackets, invalidating the JSON structure.

How could I get my code to correctly override this value while keeping it inside the square bracket?

My JSON File

{
"isVisible": false,
"Name": "Lorem ipslum",
"Int": 0,
"IdList": [10, 30, 70],
"UseKeys": true,
}

My PHP code

<?php

$commandline = ($_GET[("string")]);
$json_object = file_get_contents('file.json');

$data = json_decode($json_object, true);
$data['IdList'] = $commandline;
$json_object = json_encode($data, JSON_UNESCAPED_UNICODE);
file_put_contents('file.json', $json_object);
echo('success');
?>

When i try to change IdList to '70, 80, 90' for example, the Json file is saved like this:

"IdList":"70, 80, 90"

It should be saving like this:

"IdList": [70, 80, 90]

When I try to modify the text from the other values, it works normally.

CodePudding user response:

you are setting a string for "IdList"

this would work for you:

$data['IdList'] = array_map('intval', explode(',',$commandline));

CodePudding user response:

You can replace this line:

$data['IdList'] = $commandline;

With:

$data['IdList'] = json_decode('[' . $commandline . ']', true);
  • Related