1

I'm trying to pass an Object to the server with html post. I've already serialized the object and verified that there were no errors in that process. After I hit the submit button I receive a json string with several escape slashes and I don't know why or how I can prevent that from happening. I'm using node.js and the express module.

This is a snippet of the output I get.

{"obj":"{\"nodes\":[{\"id\":0,\"role\":\"sensor\",\"spy\":false,\"correctData\":true,\"port\":8000,\"requiresData\":[],\"connectedTo\":[]},<

HTML:Post

    <form action="/result" method="post" enctype="json" autocomplete="off">
    <input id="obj"  name="obj" required>
    <button type="button" name="action" value="getResult"
     onclick="generateJSON(true)">generateJSON </button>
    <button>Generiere Knoten</button>
    </form>

Javascript:

    function generateJSON(loaded){
        if(loaded) {
            var stuff = {nodes: localData, edges: localEdges};
            stuff = JSON.stringify(stuff);
            console.log("Result?:" + stuff);
            $('#obj').val(stuff);
        }
    }

It should be noted that the json string presented in that input field looks perfectly fine. Snippet:

{"nodes":[{"id":0,"role":"sensor","spy":false,"correctData":true,"port":8000,"requiresData":[],"connectedTo":[]},

I found this answer which helped me initially since I made the same mistake but somehow I'm still missing something.

Edit: Found a solution

I found a way to delete those backslashes and thus got a working json again. Leslie pointed me in the right direction - thanks again. I'm still unsure why this happens in the first place.

myJSONString = myJSONString.replace(/\\/g, "");
Community
  • 1
  • 1
Shiroco
  • 21
  • 1
  • 6
  • Is the problem with the server code or the browser code? If server, post code for server. You may also try losing 'enctype' as it is pretty new and most Express examples don't use it. – Jason Livesay Feb 08 '17 at 22:29
  • I don't know JSON, but do these StackOverflow threads have any helpful information: http://stackoverflow.com/questions/18325297/how-do-i-remove-backslashes-from-a-json-string http://stackoverflow.com/questions/7282755/how-to-remove-backslash-on-json-encode-function – Leslie Feb 08 '17 at 22:39
  • Thanks, Leslie. Those links got me on the right track to solve this. I'm still unsure why this happens but with "myString.replace()" I was able to at least work around this. – Shiroco Feb 08 '17 at 23:17

0 Answers0