Search code examples
javascripthtmlgreasemonkey

Extract JSON from HTML Source in JavaScript


I am in the process of building a simple Greasemonkey plugin that should do X action depending on a 'value' on the source of a page. Specifically, in the below, I would like to get at the 'value':

<script type="application/ld+json">
[
    {
      "value": "PEAR"
    }
]
</script>

In this case, reading PEAR to a variable. Thereafter, doing some logic.

Is there an approach in Javascript that would work as this value isnt necessarily 'shown' on the page.


Solution

  • You would need to get the text content of the script tag and convert it to array using JSON.parse()

    var txt = document.querySelector('script[type="application/ld+json"]').textContent
    var arr = JSON.parse(txt)
    console.log(arr[0].value)
    <script type="application/ld+json">
    [
        {
          "value": "PEAR"
        }
    ]
    </script>