【问题标题】:How can I edit the JSON of a file in PHP?如何在 PHP 中编辑文件的 JSON?
【发布时间】:2015-03-01 03:47:49
【问题描述】:

我环顾四周,找到了函数file_get_contents 和file_put_contents,并尝试编写一个基本代码,将我的代码中[0]['Face'] 的Name 更改为“Testing Face”,但它完全覆盖了JSON .

这是我在 PHP 代码之前的 JSON:

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

应该改成

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

但是,整个 JSON 被替换为 [{"Face":{"Name":"No"}}]

我的 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);
?>

谢谢!

【问题讨论】:

    标签: php arrays json file object


    【解决方案1】:

    您的 JSON 存在语法错误。具体如下:

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

    您必须删除包含"Gear" 的第一对花括号。最后一个{ 没有} 朋友。

    固定 JSON:

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

    接下来,您需要使用json_decode的第二个参数将返回的对象转换为关联数组:

    $data = json_decode($jsonString, true);
    

    阅读更多here。 (参见$assoc 参数。)

    【讨论】:

      【解决方案2】:

      将json_deconde的第二个参数添加为true(当为TRUE时,返回的对象将被转换为关联数组。)

      阅读更多内容:

      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);
      ?>
      

      【讨论】:

      • 他在 json_decode 中将stdClass 转换为array,这解决了我的问题。谢谢!
      • 他在json_decode() 中设置了可选参数,该参数确定所有对象都应该被解码为关联数组。它允许$data[0]['Face']['Name'] 工作。但是,这不是必需的,您可以简单地使用 $data[0]-&gt;Face-&gt;Name = 'Testing Face' 代替(这也看起来更清洁 imo)。但这不是问题,AJAX 有错误,这就是为什么它一开始就没有被解码。
      猜你喜欢
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 2021-08-18
      相关资源
      最近更新 更多