Search code examples
angularjsjsonstringhttpput

Convert a String to JSON object for the data element of an Angular $http.put


Right now I have the following code. I need to send a string to the body of my put request. The string needs to be valid json. The problem I had was that the message was coming through as foo instead of "foo". I did the following hack below to throw a double quote in the begging and end. Is there a better way to do this in angularjs 1.5?

 var pushMessage = function (message) {

        var data = '"' + message + '"';//this doesnt seem ideal

        var apiPath = "http://" + $location.host() + ":" + $location.port() + "/api/setMessage";
        return $http.put(apiPath, data).then(function (response) {
            return response.data;
        });
    };

Solution

  • If the message is a json you can stringify it like

    var data = JSON.stringify(message);
    

    You will need to use JSON a lot if you are going to write the JavaScript and the best place to start is MDN MOZILLA