json_decode() - 我做错了什么?

时间:2017-10-07 17:51:23

标签: php json api codeigniter

所以我决定在Codeigniter中创建自己的帮助程序以获取JSON文件并将PokeAPI调用保存为JSON。

我创建的保存JSON方法工作正常:

if ( ! function_exists('saveJson')) {
    function saveJson($file, $data) {
      $fp = fopen($file, 'w');
      fwrite($fp, json_encode($data));
      fclose($fp);
    }
}

然而,getJSON函数非常随机。它适用于获取某些文件,但其他文件会抛出此错误:消息:json_decode()期望参数1为字符串,给定数组。(所有json文件格式相同)

getJSON函数:

if ( ! function_exists('getJson')) {
    function getJson($file) {
      $json = file_get_contents($file);
      $data = json_decode($json, true);
      $pkm = json_decode($data, true);
      return $pkm;
    }
}

奇怪的是,我必须对JSON进行两次解码,否则我无法在视图中访问该数组。

我的模型和控制器有关问题的进一步深入: 模型函数示例:

function getPokemonById($id) {
      $filepath = './assets/jsonsaves/pokemoncalls/'. $id. '.json';
      if(file_exists($filepath)) {
        $pokemonByIdData = getJson($filepath);
      } else {
        $url = $this->pokemonApiAddress.$id.'/';
        $response = Requests::get($url);
        saveJson($filepath, $response);
        $pokemonByIdData = json_decode($response->body, true);
      }
      return $pokemonByIdData;
    }

控制器功能示例:

public function viewPokemon($id) {
        $singlePokemon['pokemon'] = $this->pokemon_model->getPokemonById($id);
        $singlePokemon['species'] = $this->pokemon_model->getPokemonSpecies($id);
        $data['thepokemon'] = $this->pokemon_model->getAllPokemon();
    $this->load->view('template/header', $data);
        $this->load->view('pokemonpage', $singlePokemon);
    $this->load->view('template/footer');
    }

因此我的JSON文件存在一些变化。在一个不起作用的JSON文件中,它在开头:

{"body":"{\"forms\":[{\"url\":\"https:\\\/\\\/pokeapi.co\\\/api\\\/v2\\\/pokemon-form\\\/142\\\/\",\"name\":\"aerodactyl\"}],...

然而这个有效:

"{\"forms\":[{\"url\":\"https:\\\/\\\/pokeapi.co\\\/api\\\/v2\\\/pokemon-form\\\/6\\\/\",\"name\":\"charizard\"}],...

1 个答案:

答案 0 :(得分:1)

由于@ccKep,我解决了这个问题。

我从saveJSON函数中删除了JSON编码,如下所示:

if ( ! function_exists('saveJson')) {
    function saveJson($file, $data) {
      $fp = fopen($file, 'w');
      fwrite($fp, $data);
      fclose($fp);
    }
}

然后从我的getJSON函数中删除第二个json_decode:

if ( ! function_exists('getJson')) {
    function getJson($file) {
      $json = file_get_contents($file);
      $data = json_decode($json, true);
      return $data;
    }
}

这解决了我收到的错误。