-1

I'm confused, cannot add correctly new objects to the json object:

$old_json = json_decode(file_get_contents("file.json"), true);

$new_json = ' { "1" : "111", "2" : "222" } ';
$old_json[] = $new_json;

file_put_contents("file.json", stripslashes(json_encode($old_json)));

it will replace the old records with new records, but I want just to add new record. I want it to write new json file with below content:

[{"a":"aaa","b","bbb"},{"1":"111","2":"222"}]

Please tell me how to achieve the right results. Also please show me how I can access new json object after json_decode()

Thanks.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Jigberto
  • 1,513
  • 7
  • 27
  • 50
  • 1
    What's the `stripslashes` for? How does the original input look? Why not append as a normal array after decoding? – mario Apr 13 '13 at 01:47
  • For one thing, you have an extra `)` in `file_put_contents("file.json", stripslashes(json_encode($old_json)));` at the end, unless it's part of another opening `function`? – Funk Forty Niner Apr 13 '13 at 01:49

1 Answers1

1

When a string is converted from json to a php variable with json_decode, this process produces a stdClass Object. Simply put you wouldn't want to add to the object (heres why). Although you could manipulate the stdClass Object and then reproduce a new json object.

Community
  • 1
  • 1
classicjonesynz
  • 4,012
  • 5
  • 38
  • 78