如何将JSON文件转换为arraylist

时间:2019-06-20 18:04:39

标签: javascript json

我想将JSON文件转换为一个数组列表,然后可以访问该列表并用于在网页上显示信息。

我的html文件

var xmlhttp = new XMLHttpRequest();
 xmlhttp.onreadystatechange = function() {
 if(this.readyState == 4 && this.status == 200) {
    console.log(JSON.parse(this.responseText))
}
};
 xmlhttp.open("GET", "PATIENT51.txt", true);
 xmlhttp.send(); 

我的JSON文件

{
“resourceType”:”RiskAssessment”,
“Notes”: [
{“date”: “05/13/2019”, “note”: “my notes”},
{“date”: “02/22/2018”, “note”: “cool”}
]
}

我曾尝试使用

来访问05/13/2019
myObj.Notes[0].note;

但是我得到的结果是“未定义”,我希望能够使用日期制作表格-每个日期都会有一个与之相关的注释。

1 个答案:

答案 0 :(得分:2)

请勿使用平衡引号,否则它们在json “ and ”中被称为无效的JSON chatarters。使用普通引号。 '“'

JSON.parse('{ \
“resourceType”:”RiskAssessment”, \
“Notes”: [ \
{“date”: “05/13/2019”, “note”: “my notes”}, \
{“date”: “02/22/2018”, “note”: “cool”} \
] \
}');

在chrome内为我提供了预期的错误:

  

VM18:1 Uncaught SyntaxError:位置2的JSON中出现意外令牌
      在JSON.parse()
      在js:13

使用普通引号"

然后,当您在console.log中分析输出的对象时,您会看到要从中检索值的元素称为“注释”,而不是注释。因此,您需要使用myObj.Notes[0].note来访问您感兴趣的变量。

myObj = JSON.parse('{ \
"resourceType":"RiskAssessment", \
"Notes": [ \
{"date": "05/13/2019", "note": "my notes"}, \
{"date": "02/22/2018", "note": "cool"} \
] \
}');
console.log(myObj);
console.log(myObj.Notes[0].note);

如果您希望通过使用文件替换代码段中的大括号/平衡引号,则可以使用以下答案中的解决方案:https://stackoverflow.com/a/9401374/1356107

var xmlhttp = new XMLHttpRequest();
 xmlhttp.onreadystatechange = function() {
 if(this.readyState == 4 && this.status == 200) {
    console.log(JSON.parse(this.responseText.replace(/[\u2018\u2019\u201C\u201D]/g, '"')));
}
};
 xmlhttp.open("GET", "PATIENT51.txt", true);
 xmlhttp.send(); 

但是理想情况下,生成PATIENTS1.txt的任何内容都应使用普通引号而不是平衡引号。