zoukankan      html  css  js  c++  java
  • PHP解码Json(json_decode)字符串返回NULL的原因及解决方法(转载)

    本文主要为大家讲解了php在使用json_decode函数解码json字符串时,解码不成功返回NULL的问题原因分析和解决方法,感兴趣的同学参考下.

    一般来说,php对json字符串解码使用json_decode()函数,第一个参数传字符串,第二个参数若为true,返回array;若为false,返回object。如果返回NULL,说明报错,输出json_last_error(),得到的整数值对应错误提示。如下图所示:

    json_last_error()比较常见的是整数4, 是json字符串在json_decode之前已不完整,所以语法错误。

    那么一定是客户端提交的个别字符影响了json的格式,可以使用JS进行过滤,可以解决一般问题,主要过滤回车,空格,html标签。

    /*
    * 过滤函数
    */
    function htmlEncode(str) {
      str = str.replace(/s+/ig, '');
      str = str.replace(/&/g, '');
      str = str.replace(/</g, '');
      str = str.replace(/>/g, '');
      str = str.replace(/(?:t| |v|r)*n/g, '<br />');
      str = str.replace(/t/g, '    ');
      str = str.replace(/x22/g, '"');
      str = str.replace(/x27/g, ''');
      str = str.replace(/"/g, "");
      return str;
    }
    

      

    以上情况针对的是,你必须提交json字符串数据到服务端处理,只能在客户端进行过滤。

    其它的json_decode($str)返回NULL的一些原因:

    1.$str只能UTF-8编码

    2.元素最后不能有逗号(与php的array不同)

    3.元素不能使用单引号

    4.元素值中间不能有空格和n,必须替换

  • 相关阅读:
    接口测试小结
    UI自动化例子
    SQL Server 索引结构及其使用(二)
    SQL Server 索引结构及其使用(一)
    SQL Server 索引结构及其使用(四)
    SQL Server 索引结构及其使用(三)
    SQL Server 索引和视图
    Nginx 代理配置
    Java常见框架和工具
    MYSQL 存储过程 范例
  • 原文地址:https://www.cnblogs.com/jamesbd/p/4185342.html
Copyright © 2011-2022 走看看