来自json文件的php json_decode不起作用

时间:2017-05-12 20:28:29

标签: php json

我有一个像test.json这样的文件:

{
    {"code":"ab","name":"Abkhaz","nativeName":"аҧсуа"},
    {"code":"aa","name":"Afar","nativeName":"Afaraf"},
    {"code":"af","name":"Afrikaans","nativeName":"Afrikaans"},
    {"code":"ak","name":"Akan","nativeName":"Akan"},
    {"code":"sq","name":"Albanian","nativeName":"Shqip"},
    {"code":"am","name":"Amharic","nativeName":"አማርኛ"}
}

我需要在php中转换一个数组。

为此,我试过了,但没有工作

$string = file_get_contents("test.json");
$json_array = json_decode($string, true);

print_r($json_array); //return empty
echo count($json_array); //return 0

1 个答案:

答案 0 :(得分:1)

这是有效的JSON(使用http://pro.jsonlint.com/来检查你的JSON字符串,你需要一个开始和结束括号[]而不是花括号{}):

[
    {
        "code": "ab",
        "name": "Abkhaz",
        "nativeName": "аҧсуа"
    },
    {
        "code": "aa",
        "name": "Afar",
        "nativeName": "Afaraf"
    },
    {
        "code": "af",
        "name": "Afrikaans",
        "nativeName": "Afrikaans"
    },
    {
        "code": "ak",
        "name": "Akan",
        "nativeName": "Akan"
    },
    {
        "code": "sq",
        "name": "Albanian",
        "nativeName": "Shqip"
    },
    {
        "code": "am",
        "name": "Amharic",
        "nativeName": "አማርኛ"
    }
]