0

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.

2 Answers 2

1

you are setting a string for "IdList"

this would work for you:

$data['IdList'] = array_map('intval', explode(',',$commandline));
Sign up to request clarification or add additional context in comments.

1 Comment

Works great for the problem I was having. Thank you! :D
1

You can replace this line:

$data['IdList'] = $commandline;

With:

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

1 Comment

Your solution was helpful and I will definitely use it soon for other scenarios. Thanks a lot for your contribution :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.