How do I make a string element-property's value output as an object

I suspect I’m missing something pretty simple here but I’m drawing a blank.

TLDR version : In the plugin editor, how do I convert a string property value to an object?

Details:
I have the following basic plugin-element code (2 versions). As the comments in the code explain, in the first version I have hard-coded the value of a const (MyData) as an object. When I display this in the console, it is correctly displayed as an object. See green highlight in the screenshot below.

Now in the second version, I try to do the same but by getting the value of the constant (myPropData) from a text property of the element. This time however the output in the console is a string (see red highlight in screenshot below) and I need it to be an object. I have tried JSON.parse but get an error indicating that it is not valid JSON. I have tried JSON.stringify and then JSON.parse but I still get a string.

// Code version 1 - hardcoded (static text) object value
    const MyData = {
    items: [
    {
      id: "item1",
      priority: "high",
      color: "red"
    },
    {
      id: "item2",
      priority: "low",
      color: "green"
    }
    ],
    status: { overallColor: "red", problemItemsCount: 1 }
    };
    console.log("MyData version 1 is: ");
    console.log(MyData); // Correctly outputs as an object. See green highlight in screenshot.


// Code version 2 - dynamic text as property value
    const myPropData = properties.my_data; //my_data is a text property of my element and I have set it to the same text as above
    console.log("MyData version 2 is: ");
    console.log(myPropData); // Outputs as a string. See red highlight in screenshot. How can I manipulate the my_data property's value to get it to output 	as an object just like MyData?
}

image

JSON.parse is what you are looking for. If it says that it’s invalid json it means it’s invalid json.
Look for an online json validator.
Quick tip: check that every property key is surrounded by double quotes.

1 Like

Thanks @dorilama. I won’t have full control of the input data, though it will have a fixed format, so I’m stuck with having to manipulate it after. A json validator is a good shout - I’ll give that a go.

I had hoped that JSON.stringify would ensure this but apparently not - perhaps again because the JSON isn’t valid to begin with…

1 Like