繁体   English   中英

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

[英]file upload convert string data to json data javascript

我正在加载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])

        }
        })

您正在使用

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"> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM