Sam
Sam

Reputation: 231

How can I edit the JSON of a file in PHP?

I looked around and found the functions file_get_contents and file_put_contents, and tried to make a basic code to change the Name of [0]['Face'] in my code to 'Testing Face', but it overwrites the JSON entirely.

This is my JSON prior to the PHP code:

[{"Hat":{"Name":"Stylin' Shades","Id":"221177193"},{"Gear":{"Name":"Red Sparkle Time Claymore", "Id":"221181437"}}, {"Face":{"Name":"Joyful Smile", "Id":"209995366"}]

It should be changing to

[{"Hat":{"Name":"Stylin' Shades","Id":"221177193"},{"Gear":{"Name":"Red Sparkle Time Claymore", "Id":"221181437"}}, {"Face":{"Name":"Testing Face", "Id":"209995366"}]

But instead, the entire JSON is replaced with [{"Face":{"Name":"No"}}]

My PHP:

<?php
$file = 'notifier.json';
$jsonString = file_get_contents($file);
$data = json_decode($jsonString);
$data[0]['Face']['Name'] = 'Testing Face';
$newJSON = json_encode($data);
file_put_contents($file, $newJSON);
?>

Thanks!

Upvotes: 1

Views: 167

Answers (2)

rgajrawala
rgajrawala

Reputation: 2188

Your JSON has a syntax error. Specifically this:

...,{"Gear":{"Name":"Red Sparkle Time Claymore", "Id":"221181437"}}, {"...

You have to remove the first pair of curly braces enclosing "Gear". The last { doesn't have a } friend.

Fixed JSON:

[{"Hat":{"Name":"Stylin' Shades","Id":"221177193"},"Gear":{"Name":"Red Sparkle Time Claymore", "Id":"221181437"}, "Face":{"Name":"Joyful Smile", "Id":"209995366"}}]

Next, you need to convert the returned objects into associative arrays using the second argument of json_decode:

$data = json_decode($jsonString, true);

Read more here. (See $assoc argument.)

Upvotes: 3

Adrian Cid Almaguer
Adrian Cid Almaguer

Reputation: 7791

Add the second param to json_deconde to true (When TRUE, returned objects will be converted into associative arrays. )

Read More in:

http://php.net/manual/en/function.json-decode.php

<?php
$file = 'notifier.json';
$jsonString = file_get_contents($file);
$data = json_decode($jsonString, true);

$data[0]['Face']['Name'] = 'Testing Face';

$newJSON = json_encode($data);
file_put_contents($file, $newJSON);
?>

Upvotes: 1

Related Questions