json文件格式错误 - 如何找出哪里?

时间:2017-04-06 11:30:31

标签: php json

我正在使用weatherapi开发网站。我打算使用citylist在citylist.json文件中获取天气。用户将输入城市名称,我希望从这个json中提取cityid并使用cityid来获取使用api的天气。但是json有一些错误。

    if (file_exists('citylist.json')) {

        $cityArray = file_get_contents("citylist.json");

        $cityAA = json_decode($cityArray,true);

            switch (json_last_error()) {
                case JSON_ERROR_NONE:
                    echo ' - No errors';
                break;
                case JSON_ERROR_DEPTH:
                    echo ' - Maximum stack depth exceeded';
                break;
                case JSON_ERROR_STATE_MISMATCH:
                    echo ' - Underflow or the modes mismatch';
                break;
                case JSON_ERROR_CTRL_CHAR:
                    echo ' - Unexpected control character found';
                break;
                case JSON_ERROR_SYNTAX:
                    echo ' - Syntax error, malformed JSON';
                break;
                case JSON_ERROR_UTF8:
                    echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
                break;
                default:
                    echo ' - Unknown error';
                break;
            }
        print_r($cityAA);               
    }

json大概是12mb。这是前几行

{
    "_id": 14256,
    "coord": {
        "lon": 48.570728,
        "lat": 34.790878
    },
    "country": "IR",
    "geoname": {
        "cl": "P",
        "code": "PPL",
        "parent": 132142
    },
    "langs": [{
        "de": "Azad Shahr"
    },
    {
        "fa": "آزادشهر"
    }],
    "name": "Azadshahr",
    "stat": {
        "level": 1.0,
        "population": 514102
    },
    "stations": [{
        "id": 7030,
        "dist": 9,
        "kf": 1
    }],
    "zoom": 10
}{
    "_id": 18918,
    "coord": {
        "lon": 34.058331,
        "lat": 35.012501
    },
    "country": "CY",
    "geoname": {
        "cl": "P",
        "code": "PPL",
        "parent": 146615
    },
    "langs": [{
        "en": "Protaras"
    },
    {
        "ru": "Протарас"
    }],
    "name": "Protaras",
    "stat": {
        "level": 1.0,
        "population": 20230
    },
    "stations": [{
        "id": 5448,
        "dist": 42,
        "kf": 1
    }],
    "zoom": 6
}

我已经尝试过jsonlint但是文件太大我想。 var_dump建议语法错误,格式错误的JSON。我不能发布图像,因为我不被允许。

如何找出json畸形的位置?

4 个答案:

答案 0 :(得分:2)

此网站可以为您提供帮助:http://jsonlint.com/

在提供的示例中,您不能像过去那样传递2个对象。你需要将它放在一个数组中。

 [obj,obj2]

修正:

[{
    "_id": 14256,
    "coord": {
        "lon": 48.570728,
        "lat": 34.790878
    },
    "country": "IR",
    "geoname": {
        "cl": "P",
        "code": "PPL",
        "parent": 132142
    },
    "langs": [{
        "de": "Azad Shahr"
    }, {
        "fa": "آزادشهر"
    }],
    "name": "Azadshahr",
    "stat": {
        "level": 1.0,
        "population": 514102
    },
    "stations": [{
        "id": 7030,
        "dist": 9,
        "kf": 1
    }],
    "zoom": 10
}, {
    "_id": 18918,
    "coord": {
        "lon": 34.058331,
        "lat": 35.012501
    },
    "country": "CY",
    "geoname": {
        "cl": "P",
        "code": "PPL",
        "parent": 146615
    },
    "langs": [{
        "en": "Protaras"
    }, {
        "ru": "Протарас"
    }],
    "name": "Protaras",
    "stat": {
        "level": 1.0,
        "population": 20230
    },
    "stations": [{
        "id": 5448,
        "dist": 42,
        "kf": 1
    }],
    "zoom": 6
}]

答案 1 :(得分:1)

看起来该文件包含多个JSON对象,但没有很好地集成。

这是有效的JSON:

{
    "_id": 14256,
    "coord": {
        "lon": 48.570728,
        "lat": 34.790878
    },
    "country": "IR",
    "geoname": {
        "cl": "P",
        "code": "PPL",
        "parent": 132142
    },
    "langs": [{
        "de": "Azad Shahr"
    },
    {
        "fa": "آزادشهر"
    }],
    "name": "Azadshahr",
    "stat": {
        "level": 1.0,
        "population": 514102
    },
    "stations": [{
        "id": 7030,
        "dist": 9,
        "kf": 1
    }],
    "zoom": 10
}

这也是:

{
    "_id": 18918,
    "coord": {
        "lon": 34.058331,
        "lat": 35.012501
    },
    "country": "CY",
    "geoname": {
        "cl": "P",
        "code": "PPL",
        "parent": 146615
    },
    "langs": [{
        "en": "Protaras"
    },
    {
        "ru": "Протарас"
    }],
    "name": "Protaras",
    "stat": {
        "level": 1.0,
        "population": 20230
    },
    "stations": [{
        "id": 5448,
        "dist": 42,
        "kf": 1
    }],
    "zoom": 6
}

但它们是如何组合在一起的,事实并非如此。这可能是导入JSON文件的问题,或者您是自己从API生成它。

有效的JSON将形成为这些对象的数组:

[{
    "_id": 14256,
    "coord": {
        "lon": 48.570728,
        "lat": 34.790878
    },
    "country": "IR",
    "geoname": {
        "cl": "P",
        "code": "PPL",
        "parent": 132142
    },
    "langs": [{
        "de": "Azad Shahr"
    }, {
        "fa": "آزادشهر"
    }],
    "name": "Azadshahr",
    "stat": {
        "level": 1.0,
        "population": 514102
    },
    "stations": [{
        "id": 7030,
        "dist": 9,
        "kf": 1
    }],
    "zoom": 10
}, {
    "_id": 18918,
    "coord": {
        "lon": 34.058331,
        "lat": 35.012501
    },
    "country": "CY",
    "geoname": {
        "cl": "P",
        "code": "PPL",
        "parent": 146615
    },
    "langs": [{
        "en": "Protaras"
    }, {
        "ru": "Протарас"
    }],
    "name": "Protaras",
    "stat": {
        "level": 1.0,
        "population": 20230
    },
    "stations": [{
        "id": 5448,
        "dist": 42,
        "kf": 1
    }],
    "zoom": 6
}]

PS:您可以使用http://jsonlint.com/来检查有效的JSON。

答案 2 :(得分:0)

我尝试使用以下函数将json文件转换为多个json片段的数组

        function json_split_objects($json){
                $q = FALSE;
                $len = strlen($json);
                for($l=$c=$i=0;$i<$len;$i++)
                {   
                    $json[$i] == '"' && ($i>0?$json[$i-1]:'') != '\\' && $q = !$q;
                    if(!$q && in_array($json[$i], array(" ", "\r", "\n", "\t"))){continue;}
                    in_array($json[$i], array('{', '[')) && !$q && $l++;
                    in_array($json[$i], array('}', ']')) && !$q && $l--;
                    (isset($objects[$c]) && $objects[$c] .= $json[$i]) || $objects[$c] = $json[$i];
                    $c += ($l == 0);
                }   
                return $objects;
        }

    if (file_exists('current_cities.json')) {
        echo "here";    
        $cityJson = file_get_contents("current_cities.json");

        $city_json_data_array = json_split_objects($cityJson);

但这不起作用,下面是生成的分割数组,但它没有在代码片段之间放置逗号(,)。

Array
(
    [0] => {"_id":14256,"coord":{"lon":48.570728,"lat":34.790878},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":132142},"langs":[{"de":"Azad Shahr"},{"fa":"آزادشهر"}],"name":"Azadshahr","stat":{"level":1.0,"population":514102},"stations":[{"id":7030,"dist":9,"kf":1}],"zoom":10}
    [1] => {"_id":18918,"coord":{"lon":34.058331,"lat":35.012501},"country":"CY","geoname":{"cl":"P","code":"PPL","parent":146615},"langs":[{"en":"Protaras"},{"ru":"Протарас"}],"name":"Protaras","stat":{"level":1.0,"population":20230},"stations":[{"id":5448,"dist":42,"kf":1}],"zoom":6}
    [2] => {"_id":23814,"coord":{"lon":47.055302,"lat":34.383801},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":128222},"langs":[{"fa":"کهریز"}],"name":"Kahriz","stat":{"level":1.0,"population":766706},"stations":[{"id":7022,"dist":10,"kf":1}],"zoom":7}
    [3] => {"_id":24851,"coord":{"lon":47.9725,"lat":34.073399},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":125605},"langs":[{"fa":"نور آباد"},{"link":"http://en.wikipedia.org/wiki/Nurabad%2C_Lorestan"},{"ru":"Нурабад"}],"name":"Nurabad","stat":{"level":1.0,"population":73528},"stations":[{"id":7022,"dist":80,"kf":1},{"id":7024,"dist":75,"kf":1},{"id":7073,"dist":49,"kf":1}],"zoom":9}
    [4] => {"_id":32723,"coord":{"lon":52.309422,"lat":35.23455},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":116401},"langs":[{"fa":"ايستگاه گرمسار"}],"name":"Istgah-e Garmsar","stat":{"level":1.0,"population":49491},"stations":[{"id":7036,"dist":99,"kf":1}],"zoom":8}
    [5] => {"_id":32767,"coord":{"lon":51.56889,"lat":35.439442},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":110791},"langs":[{"fa":"قرچك"}],"name":"Qarchak","stat":{"level":1.0,"population":251834},"stations":[{"id":7032,"dist":36,"kf":1},{"id":7074,"dist":48,"kf":1}],"zoom":9}
    [6] => {"_id":41210,"coord":{"lon":49.195999,"lat":36.213001},"country":"IR","geoname":{"cl":"P","code":"PPL","parent":111452},"langs":[{"fa":"خرم درّه"}],"name":"Khorram Darreh","stat":{"level":1.0,"population":50528},"stations":[{"id":7033,"dist":76,"kf":1}],"zoom":12}
    [7] => {"_id":50672,"coord":{"lon":44.893799,"lat":2.6185},"country":"SO","geoname":{"cl":"P","code":"PPL","parent":51966},"langs":[{"so":"Wanlaweyn"}],"name":"Wanlaweyn","stat":{"level":1.0,"population":22022},"zoom":9}
    [8] => {"_id":52867,"coord":{"lon":44.529991,"lat":1.78784},"country":"SO","geoname":{"cl":"P","code":"PPLA2","parent":51966},"langs":[{"so":"Qoryooley"}],"name":"Qoryooley","stat":{"level":1.0,"population":51720},"zoom":8}
    [9] => {"_id":53157,"coord":{"lon":49.872822,"lat":11.47197},"country":"SO","geoname":{"cl":"P","code":"PPL","parent":64661},"langs":[{"link":"http://en.wikipedia.org/wiki/Qandala"},{"so":"Qandala"}],"name":"Qandala","stat":{"level":1.0,"population":15923},"zoom":8}
    [10] => {"_id":53654,"coord":{"lon":45.34375,"lat":2.03711},"country":"SO","geoname":{"cl":"P","code":"PPLC","parent":64833},"name":"Mogadishu","stat":{"level":1.0,"population":2587183},"zoom":1}
    [11] => {"_id":54715,"coord":{"lon":42.544498,"lat":3.79376},"country":"SO","geoname":{"cl":"P","code":"PPL","parent":58802},"name":"Luuq","stat":{"level":1.0,"population":33820},"zoom":8}
    [12] => {"_id":55671,"coord":{"lon":42.545361,"lat":-0.35817},"country":"SO","geoname":{"cl":"P","code":"PPLA","parent":56083},"langs":[{"de":"Kismaayo"},{"en":"Kismayo"},{"es":"Kismaayo"},{"fi":"Kismayo"},{"fr":"Kismaayo"},{"id":"Kismaayo"},{"ja":"キスマヨ"},{"link":"http://en.wikipedia.org/wiki/Kismayo"},{"nl":"Kismayo"},{"so":"Kismaayo"},{"sw":"Kismayu"}],"name":"Kismaayo","stat":{"level":1.0,"population":234852},"zoom":6}
    [13] => {"_id":56166,"coord":{"lon":42.785351,"lat":0.48829},"country":"SO","geoname":{"cl":"P","code":"PPL","parent":56084},"langs":[{"link":"http://en.wikipedia.org/wiki/Jilib"},{"ru":"Джилиб"}],"name":"Jilib","stat":{"level":1.0,"population":43694},"zoom":9}
    [14] => {"_id":56335,"coord":{"lon":45.500481,"lat":2.78087},"country":"SO","geoname":{"cl":"P","code":"PPLA","parent":51967},"langs":[{"de":"Giohar"},{"en":"Giohar"},{"link":"http://en.wikipedia.org/wiki/Jowhar"},{"so":"Jawhar"}],"name":"Jawhar","stat":{"level":1.0,"population":47086},"zoom":8}
    [15] => {"_id":56399,"coord":{"lon":42.744968,"lat":0.06968},"country":"SO","geoname":{"cl":"P","code":"PPL","parent":56083},"langs":[{"de":"Jamaame"},{"en":"Jamaame"},{"link":"http://en.wikipedia.org/wiki/Jamame"}],"name":"Jamaame","stat":{"level":1.0,"population":185270},"zoom":6}

我正在考虑使用用户输入的$ city变量来获取“_id”

        for($i = 0, $size = count($city_json_data_array); $i < $size; ++$i) {
            if ($city_json_data_array[$i].['name'] == $city){
                $cityId = $city_json_data_array[$i]['_id'];
                print_r($cityId);
            }
        }

答案 3 :(得分:0)

所以JSON文件确实不正确,我不得不使用str_replace()并使用file_put_contents()编写文件来创建一个新的有效json文件。

这是我的工作代码

if (isset($_GET['city']) && $_GET['city']){        

    $city = ucwords($_GET['city']);

    if (file_exists('currentCityArray.json')) {

        $cityArray = file_get_contents("currentCityArray.json");
        $decodedArray="";   
        $decodedArray = json_decode($cityArray, true);
        //print_r($decodedArray);
        //Search the $decodedArray to match city name entered by the user and fetch the cityID for that city
        for($i = 0, $size = count($decodedArray);$i<$size; $i++) {
            if ($decodedArray[$i]['name'] == $city){

                $cityId = $decodedArray[$i]['_id'];

            }
        }

        if(!$cityId){

            $error .= $city." city could not be found in our database. Please enter a valid city name.";

        }else{
            //Fetch the weather contents by using $cityId   

            $urlContents = file_get_contents("http://api.openweathermap.org/data/2.5/forecast?id=".urlencode($cityId)."&APPID=0934a70098e84dc720b8d7f07bb1202d");

            // added a flag 'true' to retrieve the data in $weatherArray as associative array
            $weatherArray = json_decode($urlContents, true);
            //print_r ($weatherArray);

            if($weatherArray['cod']=="200"){
            //print_r($weatherArray);

                $weatherInfo = "The weather in ".$city." is currently '".$weatherArray['list'][0]['weather'][0]['description']."'";                 
                $tempCelcius = intval($weatherArray['list'][0]['main']['temp'] - 273);
                $weatherInfo .= ". The average temperature is expected to be about: ".$tempCelcius."&deg;C";                                    
                $windSpeed = $weatherArray['list'][0]['wind']['speed'];
                $weatherInfo .= ". The wind speed is currently ".$windSpeed."m/s.";                         

            }else{

                $error .= $city." city could not be found in our database. Please enter a valid city name.";

            }

        }                           
    }else{
        $error .= "Crikey ! the file with the list of cities has gone missing!";
    }
}