[英]parsing a JSON file in javascript
This is a file (data.json) containing data formated in JSON : 这是一个文件(data.json),其中包含以JSON格式格式化的数据:
{
[
{"nom" : "marteau" , "desc" : "pour en enfoncer des clous" , "qte" : "87" , "prix" : "9"},
{"nom" : "cle de 12" , "desc" : "pour les boulons du camion" , "qte" : "25" , "prix" : "12"}
]
}
I try to parse these data in JavaScript this way : 我尝试通过JavaScript解析这些数据:
<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title> catalogue outillage </title>
<script type="text/javascript" src="oXHR.js"></script>
<script type="text/javascript">
function request(callback) {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
callback(xhr.responseText);
}
}
xhr.open("GET", "data.json", true);
xhr.send();
}
function readData(oData) {
var catalogue = JSON.parse(oData);
document.getElementById("nom").innerHTML = catalogue[0].nom;
document.getElementById("desc").innerHTML = catalogue[0].desc;
document.getElementById("qte").innerHTML = catalogue[0].qte;
document.getElementById("prix").innerHTML = catalogue[0].prix;
}
</script>
</head>
<body>
<form>
<label>Name</label> : <label id = "nom"></label><br>
<label>Description</label> : <label id = "desc"></label><br>
<label>Quantité</label> : <label id = "qte"></label><br>
<label>Prix</label> : <label id = "prix"></label><br>
<button onclick="request(readData)">Afficher json</button>
</form>
</body>
</html>
Unfortunately, xhr.responseText seem to be void. 不幸的是,xhr.responseText似乎是无效的。
@epascarello I receive this message in developer console : SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data @epascarello我在开发人员控制台中收到此消息:SyntaxError:JSON.parse:JSON数据的第1行第1列的数据意外结束
@ShanRobertson I removed the first set of curly braces. @ShanRobertson我删除了第一套花括号。 But that doesn't work. 但这是行不通的。
I've found the mistake : I removed the first set of form tag 我发现了错误:我删除了第一套表单标签
Thanks for all 谢谢大家
Your JSON isn't valid. 您的JSON无效。 You just need to remove the first set of curly braces. 您只需要删除第一组花括号。
[
{
"nom": "marteau",
"desc": "pour en enfoncer des clous",
"qte": "87",
"prix": "9"
},
{
"nom": "cle de 12",
"desc": "pour les boulons du camion",
"qte": "25",
"prix": "12"
}
]
Other than that your code looks fine. 除此之外,您的代码看起来还不错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.