简体   繁体   English

如何遍历JSON?

[英]How to traverse JSON?

I have this script: 我有这个脚本:

<script>
    function postForm() {
        $.post("rest/login", $("#myform").serialize()).done(function(data) {

            if(data.status === "OK"){
                window.location.replace("coursesform.jsp");
                alert(data);
            }
            else alert (data.status);

                //alert("Invalid credentials. Please use the same username and password you'd use for a SoCS machine.");
        });
    }
</script>

I changed what the login API brings back from simply outputting this: 我更改了登录API从仅输出以下内容后带回的内容:

{"status":"OK"}

into outputting the user id as well: 以及输出用户ID:

{"status":"{au:true, id:testtutor}"}

How can I extract "true" and "testtutor"? 如何提取“ true”和“ testtutor”?

I tried this: 我尝试了这个:

var obj = JSON.parse(status.data);

So I can do obj.au however I receive this: 所以我可以做obj.au但是我收到以下信息:

however, I receive this in the browser: 但是,我在浏览器中收到此消息:

VM701:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
{"status":"{au:true, id:testtutor}"}

Remove " around {au:true, id:testtutor}, to make it 删除{au:true,id:testtutor}周围的“

{"status":{au:true, id:"testtutor"}}

Then you will be able to get au by status.au and id by status.id 然后,您将可以通过status.au获取au并通过status.id获得id

You are getting an Error because "{au:true, id:testtutor}" is not a valid JSON it needs to be {"au":true, "id":"testtutor"} but You can't do this because you already have " around it. 您收到错误消息是因为"{au:true, id:testtutor}"不是有效的JSON,它必须是{"au":true, "id":"testtutor"}但是您不能这样做,因为您已经有“。

Your API isn't returning valid JSON, or at least not in the way you're expecting. 您的API没有返回有效的JSON,或者至少没有以您期望的方式返回。 Your keys should be strings in JSON, so you should be returning something like: 您的键应该是JSON中的字符串,因此您应该返回类似以下内容的内容:

{
  "status": {
    "au": true,
    "id": "testtutor"
  }
}

...which JSON.parse() will be able to parse. ...哪个JSON.parse()将能够解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM