首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何隔离JSON对象的不同部分?

如何隔离JSON对象的不同部分?
EN

Stack Overflow用户
提问于 2017-06-15 14:39:54
回答 2查看 673关注 0票数 0

我使用的是一个API (https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?),它为我提供了这个对象(作者随机引用):

代码语言:javascript
复制
?({"quoteText":"Life is so constructed that an event does not, cannot, will not, match the expectation. ","quoteAuthor":"Charlotte Bronte","senderName":"","senderLink":"","quoteLink":"http://forismatic.com/en/16af75b8b4/"})

我将如何将Life is so constructed that an event does not, cannot, will not, match the expectation."quoteText":隔离开来,并将其放在HTML代码中的某个地方。

隔离也是一样的:Charlotte Bronte"quoteAuthor":并将其放在我的HTML代码中。加分,有时"quoteAuthor":字段留空,不知道发生时该做什么。

我知道如何将整个JSON对象放在我的HTML代码中,我只需要一些帮助来隔离JSON对象的某些部分,并将它们分开放置。

任何帮助都将不胜感激!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-06-15 20:01:23

因为您是以JSONp格式检索,所以请记住,您需要将dataType设置为jsonp,以便jQuery能够正确地解析它。这样做之后,在jqXHR.done回调中,您可以只访问实际的JSON响应。

您所收到的只是一个对象,它包含键值对格式的数据。为了访问这个值,比如Life is so constructed that...,您必须通过它的键(即quoteText )来检索它。使用点表示法并假设对象存储在一个变量中,比如response,那么可以使用response.quoteText访问引用。见以下概念证明示例:

代码语言:javascript
复制
$(function() {
  var request = $.ajax({
    url: 'https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?',
    dataType: 'jsonp'});
    
  request.done(function(response) {
    // 'response' is the entire JSON returned
    console.log(response.quoteText);
  });
});
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

票数 0
EN

Stack Overflow用户

发布于 2017-06-15 14:48:33

您可以使用.“运算符”从JSON对象访问某些键。

在您的例子中,假设您在一个名为varquote中保存了JSON,quote.quoteText将等于"Life is so constructed that an event does not, cannot, will not, match the expectation. "

代码语言:javascript
复制
var quote = {"quoteText":"Life is so constructed that an event does not, cannot, will not, match the expectation. ","quoteAuthor":"Charlotte Bronte","senderName":"","senderLink":"","quoteLink":"http://forismatic.com/en/16af75b8b4/"};

document.querySelector("#div").innerHTML = quote.quoteText;
document.querySelector("#from").innerHTML = quote.quoteAuthor;
代码语言:javascript
复制
Quote:
<pre id="div"></pre>

From: <span id="from"></span>

你应该调查一下W3学校的JSON教程

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44570382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档