如何使用JavaScript或jQuery从JSON脚本中提取options对象?
提取JSON中options对象的实现方法
完全可以通过原生JavaScript或jQuery实现,以下是不同场景的实现代码:
场景1:JSON内容已存储为字符串变量
直接调用JSON.parse()方法解析后即可直接提取options属性:
// 其中jsonStr为存储了JSON内容的字符串变量 const jsonObj = JSON.parse(jsonStr); const targetOptions = jsonObj.options; console.log(targetOptions); // 输出提取到的options对象
建议用
try...catch包裹解析逻辑,避免JSON格式错误导致脚本运行中断。
场景2:JSON内容写在页面的application/json类型script标签中
比如页面内有如下自定义标签:
<script type="application/json" id="myJsonData"> /* 此处为你的完整JSON内容 */ </script>
原生JavaScript实现
const jsonScript = document.getElementById('myJsonData'); const jsonStr = jsonScript.textContent; const jsonObj = JSON.parse(jsonStr); const targetOptions = jsonObj.options;
jQuery实现
const jsonStr = $('#myJsonData').text(); const jsonObj = JSON.parse(jsonStr); const targetOptions = jsonObj.options;
场景3:JSON通过后端接口请求获取
原生fetch实现
fetch('你的接口请求地址') .then(res => res.json()) .then(jsonObj => { const targetOptions = jsonObj.options; // 编写options对象的后续处理逻辑 })
jQuery ajax实现
$.ajax({ url: '你的接口请求地址', dataType: 'json', success: function(jsonObj) { const targetOptions = jsonObj.options; // 编写options对象的后续处理逻辑 } })
内容的提问来源于stack exchange,提问作者J.g
相关产品推荐
相关产品推荐

