Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract application/json data through jQuery

I have the following JSON on a web page. What is best way to extract this information through jQuery?

<script type="application/json" id="user-metadata">
  {"username": "zee_162", "enrollment_mode": "audit", "upgrade_link": null, "user_id": 393900}
</script>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To use jQuery to parse the JSON, get the text() of the #user-metadata element, then JSON.parse() it:

let json = $('#user-metadata').text().trim();
let obj = JSON.parse(json);

console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="application/json" id="user-metadata">
  {"username": "zee_162", "enrollment_mode": "audit", "upgrade_link": null, "user_id": 393900}
</script>

Alternatively you can perform the same logic with plain JS. The only difference is how you target the element and retrieve its text content.

let json = document.querySelector('#user-metadata').textContent.trim();
let obj = JSON.parse(json);

console.log(obj);
<script type="application/json" id="user-metadata">
  {"username": "zee_162", "enrollment_mode": "audit", "upgrade_link": null, "user_id": 393900}
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading