代码之家  ›  专栏  ›  技术社区  ›  Mar

Actionscript:JSON解析输入无效,似乎有效

  •  2
  • Mar  · 技术社区  · 7 年前

    我有以下JSON

    {
        "extras": {
            "google.sent_time": 1502027522898,
            "custom": "{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}",
            "from": "62572096498",
            "alert": "Read More...",
            "title": "New message",
            "google.message_id": "0:2905559%2ecccafd7ecd"
         } 
    }
    

    使用

    var jsonObj:Object = JSON.parse(str);
    

    给出错误:

    SyntaxError: Error #1132: Invalid JSON parse input.
        at JSON$/parseCore()
        at JSON$/parse()
    

    其他信息,

    尽管之前和之后的解决方案都是有效的,但我尝试并有效的解决方案如下。

    var clean:String = str.split("\\").join('');
    clean = clean.replace('"custom":"{"a"', '"custom":{"a"');
    clean = clean.replace('"}","from"', '"},"from"');
    
    3 回复  |  直到 7 年前
        1
  •  2
  •   Rohìt Jíndal    7 年前

    很少观察到:

    • JSON在中提供 OP JSON object 而不是 JSON string 因此,不需要解析整个对象。
    • partialJsonObj.extras.custom

    var partialJsonObj = {
        "extras": {
            "google.sent_time": 1502027522898,
            "custom": "{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}",
            "from": "62572096498",
            "alert": "Read More...",
            "title": "New message",
            "google.message_id": "0:2905559%2ecccafd7ecd"
         } 
    };
    
    partialJsonObj.extras.custom = JSON.parse(partialJsonObj.extras.custom);
    
    var jsonObj:Object = partialJsonObj;
    
    console.log(jsonObj);
        2
  •  2
  •   cameraman    7 年前

    如果这个“JSON”是actionscript的一部分,那么它是一个 Object ,不是 JSON . JSON.parse String 作为第一个参数,传递和 相反
    如果从JSON文件加载/导入此脚本,则 方法会起作用。

    // importing the external JSON file
    function loadJSON() {
        var loader:URLLoader = new URLLoader();
        loader.addEventListener(Event.COMPLETE, decodeJSON);
        loader.load(new URLRequest("test.json"));
    }
    
    // converting to actionscript Object
    function decodeJSON(e:Event):void {
        var loader:URLLoader = URLLoader(e.target) ;
        var jsonObj:Object = JSON.parse(loader.data);
        trace(jsonObj["extras"]["custom"]["a"]["message_id"]);
    }
    
    loadJSON();
    

    如果要访问“自定义”值,请取消注释JSON文件中的双引号:

      "custom": {"a":{"message_data":"","message_id":"749","message_command":"MESSAGE"},"i":"899ec3dd"},
    
        3
  •  1
  •   Artem    7 年前

    str 已经是一个javascript对象,因此没有需要解析的内容,您可以简单地如下分配它:

    var jsonObj:Object = str;
    

    custom 属性:

    a.extras.custom = JSON.parse("{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}")