我在网页上有以下JSON。通过jQuery提取这些信息的最佳方式是什么?
<script type="application/json" id="user-metadata">
{"username": "zee_162", "enrollment_mode": "audit", "upgrade_link": null, "user_id": 393900}
</script>
要使用jQuery解析JSON,请获取#user-metadata
元素的text()
,然后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>
或者,您可以使用纯JS执行相同的逻辑。唯一的区别是如何定位元素并检索其文本内容。
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>