简体   繁体   English

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

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

Im loading a json data file and the data is read as a string. 我正在加载json数据文件,并且数据以字符串形式读取。 Im trying to convert that string into a JSON object using JSON.parse but its still the string.. 我试图使用JSON.parse将该字符串转换为JSON对象,但它仍然是字符串。

THis is the JSON file 这是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 code;- 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])

        }
        })

You are currently using 您正在使用

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

But reader.result is already a string - calling stringify on it doesn't make any sense. 但是reader.result已经是一个string -对其调用stringify没有任何意义。 Your output will just be your input, the string. 您的输出将只是您的输入,即字符串。 Instead, parse just the string, without stringifying first: 相反, 分析字符串,而不先进行字符串化:

 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