简体   繁体   English

在JSON_ENCODE输出中转义\\ n

[英]Escape \n in JSON_ENCODE output

So i try to add new record to my JSON file but when i encode files i get bunch of \\ and \\n . 所以我尝试将新记录添加到我的JSON文件中,但是当我对文件进行编码时,我会得到一堆\\\\n How can i remove those? 我如何删除那些?

JSON JSON

{
    "clients": [
        {
            "id": 1,
            "name": "Name",
            "description": "XXX",
            "services": [
                {
                    "name": "dddd",
                    "host": "ddddddd",
                    "login": "ddddd",
                    "password": "ddddd"
                },
                {
                  "name": "dddd",
                  "host": "ddddddd",
                  "login": "ddddd",
                  "password": "ddddd"
                }
            ]
        }
    ]
}

PHP PHP

  $inp = file_get_contents('app/keyring.json');
  $tempArray = json_decode($inp);
  $data = '{
    "id": 5,
    "name": "dddd ddd",
    "description": "ddd"
  }';

  array_push($tempArray->clients, $data);
  $jsonData = json_encode($tempArray, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
  file_put_contents('app/keyring.json', $jsonData);

And This results in: 结果是:

"{\n    \"id\": 5,\n    \"name\": \"dddd ddd\",\n    \"description\": \"ddd\"\n  }"

You're pushing a string to your array, instead of an object. 您正在将字符串而不是对象推入数组。 It's getting double escaped so that when the file is parsed it will still be a string, because that's what you encoded. 它被双重转义,因此在解析文件时它仍然是字符串,因为这就是您编码的内容。 Use this instead: 使用此代替:

$data = json_decode('{
  "id": 5,
  "name": "dddd ddd",
  "description": "ddd"
}');

array_push($tempArray->clients, $data);

or, if you're actually building the object in PHP and not getting it as JSON from somewhere else, you can do this: 或者,如果您实际上是在PHP中构建对象,而不是从其他地方获取它作为JSON,则可以执行以下操作:

$data = (object)[
  'id' => 5,
  'name' => 'dddd ddd',
  'description' => 'ddd',
];

array_push($tempArray->clients, $data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM