【问题标题】:JSON decoding without each function没有每个函数的 JSON 解码
【发布时间】:2010-07-14 06:17:54
【问题描述】:

大家好,我有一个 json 格式输出为

{"baseUrl":"\/","success":true}

如何获得成功的价值??

【问题讨论】:

    标签: javascript json jquery


    【解决方案1】:

    为此,您可能必须为旧浏览器版本添加 JSON 库:

    var json = JSON.parse('{"baseUrl":"\/","success":true}');
    // or
    json = {"baseUrl":"\/","success":true};
    
    alert( json.success )
    //or
    alert ( json['success'])
    

    在 jQuery ajax 中,您可以使用数据类型json。 这将直接解析代码,因此您将拥有

    /* Ajax Get-Request */
    $.ajax({
      type     : 'get',
    
      url      : "myurl.html",
    
      dataType : 'json',
    
      success  : function ( response ) 
      {
         alert ( response.success )
         alert ( response['success'])
      },
    
      // Internal Server Error / Timeout
      error  : function ( XMLHttpRequest, textStatus, errorThrown ) 
      {
        alert ( "Error \n" + textStatus );
      }
    
    });
    

    http://www.json.org/js.html

    【讨论】:

      【解决方案2】:

      给你。

      var getJsonProperty = (function(){ 
        var hasJson = (window.JSON && JSON.parse && JSON.parse.call);
        return hasJson ? function (jsonString, property) {
          return JSON.parse(jsonString)[property];
        } : function (jsonString, property) {
          return new Function("return ("+jsonString+")['"+property+"'];")();
        }
      })();
      
      
      alert (getJsonProperty('{"baseUrl":"\/","success":true}', 'success'));
      // shows `true`
      

      【讨论】:

      • 仅当您从可信来源获取 JSON 时才执行此操作。
      • 真的有人从他们认为可能对其进行脚本注入攻击的源中提取 JSON 吗?无论如何,这是预JSON.parse 兼容的,这很重要。它比替代方案eval 更安全,因为它不在本地函数范围内执行。如果需要,您始终可以解析字符串中的恶意内容,但在许多(大多数?)现实世界的情况下,您将从受信任的来源获取内容。
      猜你喜欢
      • 1970-01-01
      • 2019-11-04
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      相关资源
      最近更新 更多