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

问题描述 投票:0回答:1

我加载一个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])

        }
        })
javascript jquery html json
1个回答
0
投票

您目前正在使用

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">
© www.soinside.com 2019 - 2024. All rights reserved.