访问JSON数组中的对象时出现问题

时间:2017-02-13 18:32:44

标签: javascript json

我似乎无法弄清楚如何让这段代码片段正常工作。我正在尝试访问此json片段中的“名称”对象。任何帮助将不胜感激。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
$(document).ready(function () {
	$.getJSON('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=', function(data) {
    	$('#demo').text(data[0].Name);
    });
});
</script>
</head>
<body>

<p id="demo"></p>

</body>
</html>

3 个答案:

答案 0 :(得分:1)

使用此:

$(document).ready(function () {
    $.getJSON('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=', function(data) {
        $('#demo').text(data.query.results.quote.Name);
    });
});

答案 1 :(得分:0)

{
    "query": {
        "count": 1,
        "created": "2017-02-13T18:34:48Z",
        "lang": "es-419",
        "results": {
            "quote": {
              "name": "Blabla"

所以你有data.query.results.quote.name

答案 2 :(得分:0)

您的API调用不返回数组,它返回一个JSON对象。

尝试:{ "query": { "count": 1, "created": "2017-02-13T18:34:12Z", "lang": "en-us", "results": { "quote": { // other props... "Name": "Apple Inc.", // other props... } } } }

以下是返回的数据结构:

    using (var db = new SchoolEntities())
    {
        Student student = db.students.Single(x => x.StudentId == model.StudentId);
        student.FirstName = model.FirstName;
        student.LastName = model.LastName;
        student.EmailAddress = model.StudentEmailAddress;
        student.TeacherId = model.TeacherId;

        Teacher teacher = db.teachers.Single(x => x.TeacherId == model.TeacherId);
        teacher.FirstName = model.FirstName;
        teacher.LastName = model.LastName;
        teacher.EmailAddress = model.TeacherEmailAddress;
        teacher.SubjectId = model.SubjectId;

        Subject subject = db.subjects.Single(x => x.SubjectId == model.SubjectId);
        subject.Description = model.SubjectDescription;
        subject.Level = model.SubjectLevel;

        db.SaveChanges();
    }