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>
CodePudding user response:
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>