【问题标题】:parsing a JSON file in javascript在 javascript 中解析 JSON 文件
【发布时间】:2015-10-26 17:29:53
【问题描述】:

这是一个包含 JSON 格式数据的文件 (data.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"}
  ] 
}

我尝试以这种方式在 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>

不幸的是,xhr.responseText 似乎是无效的。

@epascarello 我在开发者控制台中收到这条消息:SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

@ShanRobertson 我删除了第一组花括号。但这不起作用。

我发现了错误:我删除了第一组表单标签

谢谢大家

【问题讨论】:

  • 在网络面板/开发者控制台中查看请求时看到了什么?
  • 所以其实根本不是JSON解析的问题,而是AJAX的问题……
  • 您的 JSON 未通过验证。试试这里:jsonlint.com 或这里:jsonformatter.curiousconcept.com
  • 为什么不使用 jQuery 处理您的 HTTP 请求?这将比处理低级 API 更容易。没有人再手动编写 XMLHttpRequests 了。
  • @alcfeoh 因为不是每个人都包含 jQuery....

标签: javascript json


【解决方案1】:

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

除此之外,您的代码看起来还不错。

【讨论】:

  • 小偷!但无论如何,我并没有将其作为答案发布,因为我希望通过将他与验证者联系起来,他会自己解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2017-07-27
  • 1970-01-01
  • 1970-01-01
  • 2018-09-18
  • 2020-05-07
  • 2011-12-05
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多