如何在PHP中正确解码json?

时间:2017-04-15 17:42:44

标签: php json

我写了这个元素但是当我想显示json时,它不起作用? 我有一个空结果 我的完整代码

     $dir = OSCOM::getConfig('dir_root', 'Shop') . $this->ModuleInfosJson . '/';

      $result = glob($dir . '*' . $module_name . '*.json');


      if (!empty($result)) {
        $delete_path = str_replace($dir, '', $result);
        $delete_extansion = str_replace('.json', '', $delete_path);
        $filename = $delete_extansion;

        foreach ($filename as $module) {
          if (is_file($dir . $module . '.json') ) {
            $json = @file_get_contents(OSCOM::getConfig('dir_root', 'Shop') . $this->ModuleInfosJson . '/' . $module . '.json', true, $this->context);

var_dump($json);

            $result_json = json_decode($json);

 var_dump($result_json);
}

结果在var_dump($ result_json);

"{ "title": "module_apps_best_selling", "type": "apps", "vendor": "", "is_free": "Yes", "website_to_sell" : "", "version": 1.0, "req_core_version": 3.0, "license": "GPL 2", "tag": "apps, module, products, listing, best selling", "install": "includes/Apps/", "module_directory": "ProductsListing", "apps_name": "\BestSelling", "type_module": "fixe", "dependance": "", "description": "This module allow you to insert a new page called Best Selling inside the catalog. It create also in the template directory a new directory where you can manage and create template.", "image": "ModuleInfosJson/apps_best_selling.png", "authors": [ { "name": "", "company": "", "email": "", "website": "", "Community": "" } ] } "
<{1}}上的

结果为var_dump($result_json)

结果NULL

print_r($json)
<{1}}上的

结果为空

服务器上的json就是那样

{ "title": "module_apps_best_selling", "type": "apps", "vendor": "", "is_free": "Yes", "website_to_sell" : "", "version": 1.0, "req_core_version": 3.0, "license": "GPL 2", "tag": "apps, module, products, listing, best selling", "install": "includes/Apps/", "module_directory": "ProductsListing", "apps_name": "\BestSelling", "type_module": "fixe", "dependance": "", "description": "This module allow you to insert a new page called Best Selling inside the catalog. It create also in the template directory a new directory where you can manage and create template.", "image": "ModuleInfosJson/apps_best_selling.png", "authors": [ { "name": "", "company": "", "email": "", "website": "", "Community": "" } ] } 

1 个答案:

答案 0 :(得分:1)

也许您需要调查json数据在源头的格式。 json_decode不允许在json数据中使用单引号,不带引号的键/名称和尾随逗号。

您可能还需要检查json_decode($json, true);是否解决了您的问题

编辑:

我看到了

您的json第13行"apps_name": "\BestSelling",看起来有错误。你需要在"\BestSelling"中逃避狂野的反斜杠。 有效的json片段为"apps_name": "\\BestSelling",

在调用json_decode之前,您需要在json数据中用\\替换任何单个反斜杠