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

文件上传将字符串数据转换为JSON数据javascript

  •  0
  • user1050619  · 技术社区  · 7 年前

    我加载一个JSON数据文件,数据作为一个字符串读取。我试图使用json.parse将该字符串转换为json对象,但它仍然是字符串。

    这是JSON文件

    {
        "annotations": {
            "a": [{
                    "AA00": [4.9724, 6.7862, 1.568737, 4.9943, 17.4203, 1.568737]
                },
                {
                    "AA01": [6.5117, 17.4155, -1.572977, 6.5584, 6.7322, -1.572977]
                },
                {
                    "AA02": [7.7934, 6.7196, 1.575093, 7.7473, 17.4463, 1.575093]
                },
                {
                    "AA03": [9.7196, 17.3718, -1.563688, 9.7145, 9.6473, -1.563688]
                },
                {
                    "AA04": [12.2965, 24.9181, -1.558673, 12.4939, 11.9399, -1.558673]
                }
                    ]
                        ,
                "p": [{"HOME": [9.60, 6.22, 0.0]}]
            }
    
    }
    

    jQuery代码;。-

    $('#annotation-file-upload').on('change', function(){
                if (this.files && this.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {      
                    console.log(typeof reader.result)
                    annotationsObject = JSON.parse(JSON.stringify(reader.result))
                    console.log(annotationsObject)
                    console.log(typeof annotationsObject)
                };
                reader.readAsText(this.files[0])
    
            }
            })
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   CertainPerformance    7 年前

    您当前正在使用

    annotationsObject = JSON.parse(JSON.stringify(reader.result))
    

    但是 reader.result 已经是 string -呼叫 stringify 在这上面没有任何意义。你的输出只是你的输入,字符串。相反,解析 只是 不先串起来的字符串:

    document.querySelector('input').addEventListener('change', function() {
      if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
          console.log(typeof reader.result)
          annotationsObject = JSON.parse(reader.result);
          console.log(annotationsObject)
          console.log(typeof annotationsObject)
        };
        reader.readAsText(this.files[0])
      }
    });
    <input type="file">