在尝试更复杂的事情之前,我想简单地掌握这个概念,所以我们只是说请求的响应是:
{
"embed": {
"code": "<iframe src="https://www.youtube.com/watch?v=dQw4w9WgXcQ" frameborder="0" width="608" height="468" scrolling="no"></iframe>"
}
}
我的下一个最好的猜测是1)在上面的代码周围抛出引号,2)将其分配给,并将其声明为变量,假设“var data”3)为解析的JSON数据声明另一个变量:
var solu = JSON.parse(data);
但除此之外,我在访问对象的元素时遇到了困难。如果这让你感到困惑,我道歉。如果我从错误的角度接近这个,请告诉我。
答案 0 :(得分:0)
您不需要使用JSON.parse(data)
,因为您已经在使用json对象。
var data = {
"embed": {
"code": '<iframe src="https: //www.youtube.com/watch?v=dQw4w9WgXcQ" frameborder="0" width="608" height="468" scrolling="no"></iframe>'.replace(/</g, '<')
},
// keys can be wrapped with string or not
key: 'got the key',
'stringKey': 'got the string identifier',
'key with spaces': 'keys can have spaces or any reserved character',
arrayOfStuff: ['thing', 'stuff', 'more']
}
// you can get data using the dot operator to nest deeper
console.log( data.embed );
// or use the array brackets syntax
console.log( data['embed'] );
// you can mix it up as both are equivelent, this will dig further into the object to code
console.log( data['embed'].code );
// if you key has reserved characters you must use the array bracket syntax
console.log( data['key with spaces'] );
// you can use arrays as well
console.log( data.arrayOfStuff[0] )
console.log( data['arrayOfStuff'][1] )
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>