0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PHP/JSON】json_decodeは余分なコンマでエラーを吐く

Posted at

作業メモです。

問題

このように、JSON ファイルを PHP で読み込もうとすると…

.json
[
  {
    "a" : "A1",
    "b" : "B1",
  },
  {
    "a" : "A2",
    "b" : "B2",
  },
]
.php
var_dump(json_decode(mb_convert_encoding(file_get_contents('.json'), 'UTF8', 'UTF-8,JIS,EUC-JP,SJIS-WIN'), true));
output
NULL

上手く処理してくれません。

原因

原因は「,」こいつです。
PHP は、配列の余分なカンマを許容してくれません。

解決策

余分なカンマを削除します。

.json
[
  {
    "a" : "A1",
    "b" : "B1"
  },
  {
    "a" : "A2",
    "b" : "B2"
  }
]

すると……

output
array(2) {
  [0]=>
  array(2) {
    ["a"]=>
    string(2) "A1"
    ["b"]=>
    string(2) "B1"
  }
  [1]=>
  array(2) {
    ["a"]=>
    string(2) "A2"
    ["b"]=>
    string(2) "B2"
  }
}

正常に動きました!

以上。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?