JSON.parse返回字符串而不是对象

时间:2021-12-18 06:46:49

im writing a websocket client and i would like to receive messages as json strings. For this I need a login. And if the login isn't true i send a json string with nosuccess. JSON String:

我正在编写一个websocket客户端,我希望以json字符串的形式接收消息。为此,我需要登录。如果登录不正确,我发送一个带有nosuccess的json字符串。 JSON字符串:

{"action":"login","args":["nosuccess"]}

On the client I'm using this to get the string:

在客户端我正在使用它来获取字符串:

WebSocket socket = new WebSocket("ws://localhost:2555/api");

socket.onmessage = function(evt) {
    console.log(evt.data);
    console.log(typeof(evt.data));
    onMessage(evt);
}
function onMessage(evt) {
var data = JSON.parse(evt.data);
var action = data.action;
var args = data.args;
console.log(data);
console.log(typeof(data));
console.log(action);
console.log(args);

But the type of data is a string... But why?

但是数据类型是一个字符串...但为什么呢?

evt.data returns:

evt.data返回:

 "{\"action\":\"login\",\"args\":[\"nosuccess\"]}"

data returns:

数据返回:

 {"action":"login","args":["nosuccess"]}

The WebSocket server is a jetty Server which sends a string and a string array in json parsed in json with gson.toJson(class) Gson by Google. The Class is a class containing String action and String array args.

WebSocket服务器是一个jetty Server,它在json中使用gson.toJson(class)Gson在json中发送一个字符串和一个字符串数组。 Class是一个包含String动作和String数组args的类。

Complete source code of websocket.js:

websocket.js的完整源代码:

var socket;

function openWebsocket(adress) {
    socket = new WebSocket(adress);
    socket.onopen = function(evt) {
        console.log("Socket opened [" + adress + "]");
    };
    socket.onclose = function(evt) {
        loadPage("login.html");
        console.log("Socket closed [" + evt.code + "]");
    }
    socket.onmessage = function(evt) {
        onMessage(evt);
    }
    socket.onerror = function(evt) {
        console.log("Socket couldn't connect [" + evt.message + "]");
        showMessage("fa-exclamation-circle", "Socket couldn't be established!", 1000);
    }
}

function onMessage(evt) {
    var data = JSON.parse(evt.data);
    var action = data.action;
    var args = data.args;
    console.log(data);
    console.log(typeof(data));
    console.log(action);
    console.log(args);
    $(".card-container h3").html(data);

    if(action == "login") {
        if(args[0] == "success") {
            loadPage("dashboard.htm");
            currentpage = "dashboard.htm";
            showMessage("fa-check", "Du wurdest erfolgreich eingeloggt", 2000);
        } else if(args[0] == "nosuccess") {
            loadPage("login.html");
            currentpage = "login.html";
            showMessage("fa-exclamation-circle", "Falscher Benutzername oder falsches Passwort", 2000);
        } else if(args[0] == "unauthenticated") {
            loadPage("login.html");
            currentpage = "login.html";
            showMessage("fa-exclamation-circle", "Login failure: not authenticated", 2000);
        }
    }

}

function sendMessage(json) {
    $(".card-container h3").html(JSON.stringify(json));
    console.log(JSON.stringify(json));
    socket.send(JSON.stringify(json));
}

If I change this line:

如果我更改此行:

 var data = JSON.parse(evt.data);

to this:

对此:

var data = JSON.parse("{\"action\":\"login\",\"args\":[\"nosuccess\"]}");

Then it is a json object, but when I use evt.data then it is a string. If I change the line to this:

然后它是一个json对象,但是当我使用evt.data时它就是一个字符串。如果我将行更改为:

    var data = JSON.parse(JSON.parse(evt.data));

Then it works, but why, normally it should do it with only one JSON.parse, should it?

然后它工作,但为什么,通常它应该只用一个JSON.parse,它应该吗?

1 个解决方案

#1


1  

As others have stated in the comments it seems that this issue has been solved. If you are receiving a response from the server as a "stringified object" then you can turn it into a normal object with JSON.parse() like so:

正如其他人在评论中所说,这个问题似乎已经解决了。如果您从服务器接收响应作为“字符串化对象”,那么您可以使用JSON.parse()将其转换为普通对象,如下所示:

var stringResponse = '{"action":"login","args":["nosuccess"]}';

var objResponse = JSON.parse(stringResponse);

console.log(objResponse.args);

You can also try out the above code here.

您也可以在这里试用上面的代码。

As for why the server is returning a string when you really wanted an object, that really comes down to your backend code, what library you are using, and the transport protocol. If you just want your front-end code to work, use JSON.parse. If you want to edit how the backend responds, please provide more information.

至于为什么服务器在您真正想要一个对象时返回一个字符串,这实际上归结为您的后端代码,您正在使用的库以及传输协议。如果您只想使用前端代码,请使用JSON.parse。如果您想编辑后端的响应方式,请提供更多信息。

#1


1  

As others have stated in the comments it seems that this issue has been solved. If you are receiving a response from the server as a "stringified object" then you can turn it into a normal object with JSON.parse() like so:

正如其他人在评论中所说,这个问题似乎已经解决了。如果您从服务器接收响应作为“字符串化对象”,那么您可以使用JSON.parse()将其转换为普通对象,如下所示:

var stringResponse = '{"action":"login","args":["nosuccess"]}';

var objResponse = JSON.parse(stringResponse);

console.log(objResponse.args);

You can also try out the above code here.

您也可以在这里试用上面的代码。

As for why the server is returning a string when you really wanted an object, that really comes down to your backend code, what library you are using, and the transport protocol. If you just want your front-end code to work, use JSON.parse. If you want to edit how the backend responds, please provide more information.

至于为什么服务器在您真正想要一个对象时返回一个字符串,这实际上归结为您的后端代码,您正在使用的库以及传输协议。如果您只想使用前端代码,请使用JSON.parse。如果您想编辑后端的响应方式,请提供更多信息。