Can't manipulate JSON object in any way

Viewed 133

I'm making a website on Cargocollective and customizing parts of it with Javascript (only vanilla allowed). I figured out Cargo stores the whole website in the same HTML using JSON notation, in <script type="text/json"> elements.

I want to extract information from those JSON objects to use in my script. I am able to select the JSON object using queryselectors. The objects looks like a JSON object, and typeof returns object.

However, if I try to do something like myObject.key, or myObject[0].key, I get "undefined". If I try to JSON.parse I get "Unexpected token o in JSON at position 1". JSON.stringify returns {}.

This is what it looks like in the HTML: (it's very long, 4000 characters, this is just an excerpt)

<script type="text/json" data-set="ScaffoldingData" >{"id":0,"title":"Sandra Javera","project_url":0,"set_id":0,"is_homepage":false,"pin":false,"is_set":true,"in_nav":false,.........},{"id":14844451,"site_id":711279,"project_url":"Lisboa-copy","direct_link":"https:\/\/sandrajavera.com\/Lisboa-copy","type":"page","title":"Lisboa copy","title_no_html":"Lisboa copy","tags":"","display":true,"pin":false,"pin_options":null,"in_nav":false,"is_homepage":false,"backdrop_enabled":false,"is_set":false,"stack":false,"excerpt":"+\n\t\t\n..........}\"</script>

So the JSON object has a structure like

{
   "key": value,
   "key": value,
   "key": value
},
{
   "key": value,
   "key": value,
   "key": value
},
{
   "key": value,
   "key": value,
   "key": value
}

so it's actually an array of objects even though there are no brackets.

The website is sandrajavera.com. Any help is appreciated. Thank you.

1 Answers

Wrap the text in [] to make the structure valid and then parse it.

Adding the wrapping array braces would be better done at the source however

const str = document.querySelector('script[data-set]').textContent.trim()
const data = JSON.parse(`[${str}]`)

console.log(data)
<script type="text/json" data-set="ScaffoldingData" >
  { "id": 1,"txt": "foo"}, { "id": 2, "txt": "bar" }
</script>

Related