如何将JSON文件转换为arraylist [英] How do I turn a JSON file into an arraylist

查看:318
本文介绍了如何将JSON文件转换为arraylist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to turn my JSON file into an arraylist that I can then access and use to display the information on the web page.

我的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"}
]
}

我曾尝试使用

myObj.Notes[0].note;

但是我得到的结果是未定义",我希望能够使用日期创建表格-每个日期都会有一个与之相关的注释.

But I get "undefined" as a result, I want to be able to make a table using the dates- each date will have a note associated with it.

推荐答案

不要使用平衡引号,或者在JSON and 中调用它们不是有效的JSON chatarters.使用普通引号. ''

Don't use balanced quotes or however they're called in json " and " are not valid JSON chatarters. use normal quotes. '"'

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

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

Gives within chrome for me the expected error:

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

VM18:1 Uncaught SyntaxError: Unexpected token " in JSON at position 2
at JSON.parse ()
at js:13

使用普通引号"

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

Then when you analyze the outputted Object in console.log you see that the element where you wish to retrieve values from is called 'Notes' and not note. So you need to use myObj.Notes[0].note to access the variable you're interested in.

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

If you wish to replace the curly/balanced quotes in your code snippet by using the file you can use the solution from this answer: 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的任何内容都应使用普通引号而不是平衡引号.

but ideally you would have whatever generates PATIENTS1.txt use normal quotes instead of balanced quotes.

这篇关于如何将JSON文件转换为arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆