Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse content within <script> with JavaScript?

For example in a webpage I have somewhere:

<script id="ajaxify-data" type="application/json">
{"key1":123,"key2":333}
</script>

Can I use javascript to parse it? (specifically, the ajaxify-data)

jQuery $("#ajaxify-data") just doesn't work here..

Edit: The website that I wanted to crawl actually is more complex than the simple example given above...

https://discuss.leetcode.com/unread looks like the web source, although containing ajaxify-data tag, it actually renders the data in ajax result instead of storing it in the actual ajax tag above.

This is what I get in the console:

> document.getElementById('ajaxify-data')
null

The webpage screenshot: https://discuss.leetcode.com/ screenshot

like image 807
Sean L Avatar asked Feb 22 '26 21:02

Sean L


1 Answers

Just JSON parse the innerHTML of the script tag.

Plain JavaScript:

var json = JSON.parse(
  document.getElementById('ajaxify-data').innerHTML
);

console.log(json);
console.log(json.key1);
<script id="ajaxify-data" type="application/json">
  { "key1": 123, "key2": 333 }
</script>

Or with jQuery:

var json = JSON.parse($('#ajaxify-data').html())

console.log(json);
console.log(json.key1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="ajaxify-data" type="application/json">
  { "key1": 123, "key2": 333 }
</script>
like image 112
KevBot Avatar answered Feb 25 '26 10:02

KevBot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!