Adam
Adam

Reputation: 13

JSON.parse() returning strings

I am trying to iterate through an array of objects and populate an HTML select element with options whose values are the entire contents of each object. The population is successful, but the objects are turned into strings in the process and I do not know how to turn them back into objects.

Running them through JSON.parse() gives me "Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse." My research suggests that this happens when you use JSON.parse() on something that is already an object, but running typeOf() on the data beforehand reveals that it is a string.

I do not get this error if I instead run the data through JSON.parse(JSON.stringify(data)), but its output remains a string.

Please help me understand what I am misapprehending about JSON.parse(). Thank you.

const selectors = document.getElementsByClassName("ingredientSelector");
const cookButton = document.getElementById("cookButton");

//very large array of ingredient objects

let selectorOptions = "<option value = 'Nothing'>Nothing</option>";
 for (let i = 0; i < ingredients.length; i++){
     selectorOptions += ("<option value = '" + ingredients[i] + "'>" + ingredients[i].name + "</option>");
 }
Array.prototype.forEach.call(selectors,function(selector){
    selector.innerHTML = selectorOptions;
});

function cook(ingredients){
    console.log("Cooking with ingredients: " + ingredients);
}

cookButton.addEventListener("click", function(){
    let ingredients = [];
    Array.prototype.forEach.call(selectors,function(selector){
        if(selector.value !== 'Nothing'){
            console.log(typeof(selector.value))
            JSON.parse(selector.value);
            let JSONString = JSON.stringify(selector.value);
            console.log(typeof(JSONString));
            let JSONObject = (JSON.parse(JSONString));
            console.log(typeof(JSONObject));
            console.log(JSONObject.name);
        }
        console.log(ingredients);
        cook(ingredients);
    });
});

Upvotes: 0

Views: 223

Answers (1)

Klaycon
Klaycon

Reputation: 11080

The issue is how you're building the value properties for the options you're inserting into each selector. On this line:

selectorOptions += ("<option value = '" + ingredients[i] + "'>" + ingredients[i].name + "</option>");

Your comment says that ingredients is an array of objects, so ingredients[i] will be an object. Concatenating an object to a string will, by default, turn it into [object Object] - and this is what's causing your error. You're ending up with an option that looks something like this, perhaps:

<option value = '[object Object]'>Raw Prime Meat<object>

There's two perfectly valid approaches here. You can either store the ingredient index in the option values, which you can then use to lookup the ingredient from your master array later, or you should use JSON.stringify(ingredients[i]) to turn the object into a JSON.parseable string to make your code work as-is.

So this would work fine:

selectorOptions += ("<option value = '" + JSON.stringify(ingredients[i]) + "'>" + ingredients[i].name + "</option>");

Upvotes: 0

Related Questions