javascriptjavascript-objectsjsonstore

Why does JSON.parse(str) into String?


I try to use JSON.parse(); to parse a string into a JavaScript object, but when I call console.log(object.constructor.name); after, it gives me "String".

I tried using parse twice rather than once, but then it gave me an error.

var userInput = document.getElementById("userInput");
var yes = document.getElementById("yes");
var no = document.getElementById("no");
var dataString = "";
const endpoint = 'https://www.jsonstore.io/4037b406bb44de85c5dd50eb1a6472bedb79f447e747412695637c2784cbe43f';

function writeToDatabase(arr) {
    alert(arr);
    (async function() {
            // Send a post request, saving some data
            post_response = await fetch(endpoint, {
                    method: 'POST',
                    headers: {
                            'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(arr)
            });
            /*
            // console.log the result
            console.log(`POST response:`, await post_response.json())
            */
    })();
}
function readFromDatabase() {
    fetch(endpoint)
    .then(response => response.json())
    .then(data => {

    console.log(data);
        dataArr = data;
        console.log(dataArr);
  });
}

yes.onclick = function() {
    fetch(endpoint)
    .then(response => response.json())
    .then(data => {

        data = JSON.stringify(data);
        console.log("full data: " + data);

        data = JSON.parse(data);
        data = data['result'];

        data = JSON.stringify(data);
        console.log("result array only: " + data);

        data = JSON.parse(data);// object.contructor.name
        console.log("after parse: " + data);
        console.log("data type is: " + data.constructor.name);

        data[userInput.value] = "YES";
        console.log("final string to write to database: " + data);
        writeToDatabase(data);
    });
}



no.onclick = function() {
    dataString = "{"+userInput.value+": "+"NO"+"}"
    writeToDatabase(dataString);
}

I expected it to convert to a Javascript Object so I could add an item, but instead, it stays as a string and so I can't add an item.

CODE: https://repl.it/@ErichBuelow/JsonStore-using-JS VIEW: https://jsonstore-using-js--erichbuelow.repl.co/


Solution

  • This is the data at the URL:

    {"result":"{test: NO}","ok":true}
    

    response.json() then converts that to a JavaScript object with two properties (result (a string) and ok (a boolean).

    data = JSON.stringify(data) converts it back to JSON, reversing the effect of response.json().

    data = JSON.parse(data); reverse it again giving you the aforementioned object ones more.

    data = data['result']; extracts the result property, giving you the string "{test: NO}".

    data = JSON.stringify(data); gives you the JSON representation of that string.

    data = JSON.parse(data); reverses that giving you the string again.

    I tried using parse twice rather than once, but then it gave me an error.

    It isn't clear where you tried this, but if you tried to parse {test: NO} then it errored because that string is not valid JSON. { "test": "NO" } would be valid JSON, but the quotes are missing.

    Having strings of JSON embedded in JSON is just silly though. It would be better to express the original JSON as:

    {
        "result": {
            "test": "NO"
        },
        "ok": true
    }