Sử dụng JSON trong Giao thức dữ liệu Google

Cảnh báo: Trang này giới thiệu về các API cũ của Google, API dữ liệu của Google; trang này chỉ liên quan đến các API được liệt kê trong thư mục API dữ liệu của Google, nhiều API trong số này đã được thay thế bằng các API mới hơn. Để biết thông tin về một API mới cụ thể, hãy xem tài liệu của API mới. Để biết thông tin về việc uỷ quyền cho các yêu cầu bằng một API mới hơn, hãy xem phần Xác thực và ủy quyền tài khoản Google.

Bài viết này đề cập đến JSON khi được sử dụng trong Giao thức dữ liệu Google. Để biết thêm thông tin về giao thức, hãy xem Hướng dẫn dành cho nhà phát triển.

Bạn có thể sử dụng JSON với bất kỳ ngôn ngữ lập trình nào, nhưng các ví dụ trong tài liệu này đều ở dạng JavaScript.

Giới thiệu về nguồn cấp dữ liệu JSON và nguồn cấp dữ liệu XML

Dịch vụ dữ liệu của Google tạo nguồn cấp dữ liệu ở định dạng JSON bằng cách chuyển đổi nguồn cấp dữ liệu XML đó bằng các quy tắc sau:

Cơ bản

  • Nguồn cấp dữ liệu được biểu thị dưới dạng một đối tượng JSON; mỗi phần tử hoặc thuộc tính lồng nhau được biểu thị dưới dạng một thuộc tính tên/giá trị của đối tượng.
  • Các thuộc tính được chuyển đổi thành thuộc tính Chuỗi.
  • Các phần tử con được chuyển đổi thành các thuộc tính Đối tượng.
  • Các phần tử có thể xuất hiện nhiều lần sẽ được chuyển đổi thành thuộc tính Array.
  • Giá trị văn bản của thẻ được chuyển đổi thành thuộc tính $t.

Vùng chứa tên

  • Nếu một phần tử có bí danh không gian tên, thì bí danh và phần tử đó sẽ được nối với nhau bằng "$". Ví dụ: ns:element trở thành ns$element.

XML

  • Phiên bản XML và thuộc tính mã hoá được chuyển đổi lần lượt thành thuộc tính phiên bản và mã hoá của phần tử gốc.

Ví dụ sau đây cho thấy các phiên bản XML và JSON của cùng một nguồn cấp dữ liệu. Các thẻ này được gắn thẻ để dễ dàng so sánh.

XML

<?xml version="1.0" encoding="UTF-8" ?>
<feed xmlns="http://www.w3.org/2005/Atom"
    xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
    xmlns:gd="http://schemas.google.com/g/2005"
    xmlns:gCal="http://schemas.google.com/gCal/2005">
  <id>...</id>
  <updated>2006-11-12T21:25:30.000Z</updated>
  <title type="text">Google Developer Events</title>
  <subtitle type="text">The calendar contains information about upcoming
    developer conferences at which Google will be speaking, along with
    other developer-related events.</subtitle>
  <link rel="http://schemas.google.com/g/2005#feed"
    type="application/atom+xml" href="..." />
  <link rel="self" type="application/atom+xml" href="..." />
  <author>
    <name>Google Developer Calendar</name>
    <email>developer-calendar@google.com</email>
  </author>
  <generator version="1.0"
    uri="http://www.google.com/calendar">Google Calendar</generator>
  <openSearch:startIndex>1</openSearch:startIndex>
  <openSearch:itemsPerPage>25</openSearch:itemsPerPage>
  <gCal:timezone value="America/Los_Angeles" />
    
  <entry>
    <id>...</id>
    <published>2006-11-12T21:25:30.000Z</published>
    <updated>2006-11-12T21:25:30.000Z</updated>
    <category scheme="..." term="..." />
    <title type="text">WebmasterWorld PubCon 2006:
      Google Developer Tools in General</title>
    <content type="text">Google is sponsoring at 
      <a href="http://www.pubcon.com/">WebmasterWorld PubCon 2006</a>. Come and
      visit us at the booth or join us for an evening demo reception where we
      will be talking "5 ways to enhance your website with Google Code". 
      After all, it is Vegas, baby! See you soon.</content>
    <link rel="alternate" type="text/html" href="..." title="alternate" />
    <link rel="self" type="application/atom+xml" href="..." />
    <author>
      <name>Google Developer Calendar</name>
      <email>developer-calendar@google.com</email>
    </author>
    <gCal:sendEventNotifications value="true" />
    <gd:comments>
       <gd:feedLink href="..." />
    </gd:comments>
    <gd:transparency value="..." />
    <gd:eventStatus value="..." />
    <gd:where valueString="3150 Paradise Road, Las Vegas, NV 89109" />
    <gd:when startTime="2006-11-15" endTime="2006-11-17">
      <gd:reminder minutes="10" />
    </gd:when>
  </entry>
  ...
</feed>
    

JSON

{
"version": "1.0", "encoding": "UTF-8", "feed": { "xmlns": "http://www.w3.org/2005/Atom", "xmlns$openSearch": "http://a9.com/-/spec/opensearchrss/1.0/", "xmlns$gd": "http://schemas.google.com/g/2005", "xmlns$gCal": "http://schemas.google.com/gCal/2005", "id": {"$t": "..."}, "updated": {"$t": "2006-11-12T21:25:30.000Z"}, "title": { "type": "text", "$t": "Google Developer Events" }, "subtitle": { "type": "text", "$t": "The calendar contains information about upcoming developer conferences at which Google will be speaking, along with other developer-related events." }, "link": [{ "rel": "...", "type": "application/atom+xml", "href": "..." },{ "rel": "self", "type": "application/atom+xml", "href": "..." }], "author": [{ "name": {"$t": "Google Developer Calendar"}, "email": {"$t": "developer-calendar@google.com"} }], "generator":{ "version": "1.0", "uri": "http://www.google.com/calendar", "$t": "Google Calendar" }, "openSearch$startIndex": {"$t": "1"}, "openSearch$itemsPerPage": {"$t": "25"}, "gCal$timezone": {"value": "America/Los_Angeles"}, "entry": [{ "id": {"$t": "..."}, "published": {"$t": "2006-11-12T21:25:30.000Z"}, "updated": {"$t": "2006-11-12T21:25:30.000Z"}, "category": [{ "scheme": "...", "term": "..." }], "title":{ "type": "text", "$t": "WebmasterWorld PubCon 2006: Google Developer Tools in General" }, "content": { "type": "text", "$t": "Google is sponsoring at <a href="http://www.pubcon.com/">WebmasterWorld PubCon 2006</a>. \nCome and visit us at the booth or join us for an evening demo reception where we will be talking "5 ways to enhance your website with Google Code".\nAfter all,\nit is Vegas, baby! See you soon." }, "link": [{ "rel": "alternate", "type": "text/html", "href": "...", "title": "alternate" },{ "rel": "self", "type": "application/atom+xml", "href": "..." }], "author": [{ "name": {"$t": "Google Developer Calendar"}, "email": {"$t": "developer-calendar@google.com"} }], "gd$transparency": {"value": "http://schemas.google.com/g/2005#event.opaque"}, "gd$eventStatus": {"value": "http://schemas.google.com/g/2005#event.confirmed"}, "gd$comments": {"gd$feedLink": {"href": "..."}}, "gCal$sendEventNotifications": {"value": "true"}, "gd$when": [{ "startTime": "2006-11-15", "endTime": "2006-11-17", "gd$reminder": [{"minutes": "10"}] }], "gd$where": [{"valueString": "3150 Paradise Road,Las Vegas,NV 89109"}]}, }] } }

Yêu cầu và sử dụng nguồn cấp dữ liệu JSON

Atom là định dạng mặc định của Google Data. Nếu không chỉ định tham số alt trong yêu cầu, thì bạn sẽ nhận được một nguồn cấp dữ liệu Atom.

Lưu ý: Thư viện ứng dụng Google Data hiện không hỗ trợ JSON.

Đầu ra JSON

Để yêu cầu phản hồi ở định dạng JSON, hãy dùng tham số alt=json.

Ví dụ: để yêu cầu nguồn cấp dữ liệu lịch nhà phát triển của Google ở định dạng JSON, hãy gửi truy vấn sau:

http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full?alt=json

Đầu ra JSON-in-script

Để yêu cầu phản hồi bao bọc JSON trong một thẻ tập lệnh, hãy sử dụng tham số alt=json-in-script và thêm một hàm gọi lại bằng cách thêm tham số callback=functionName.

http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full?alt=json-in-script&callback=myFunction

Việc sử dụng các hàm gọi lại cho phép bạn giải quyết một số vấn đề bảo mật trên nhiều miền mà bạn có thể gặp phải trong JavaScript phía máy khách thông thường. Thông thường, trình duyệt sẽ ngăn bạn tải tệp trên nhiều miền do các lỗ hổng bảo mật tiềm ẩn và các cuộc tấn công miền chéo có thể dẫn đến.

Định dạng JSON-in-script cho phép bạn khắc phục những hạn chế này bằng cách tải phản hồi trong một thẻ tập lệnh trên ứng dụng. Tức là bạn có thể dùng phản hồi ở những vị trí khác trong mã JavaScript trên trang đó. Kết quả JSON được tải khi trang được tải; không cần thủ thuật khác.

Ứng dụng làm việc đơn giản dưới đây minh hoạ kỹ thuật này:

<h3>Upcoming Google Developer Events</h3>

<div id="agenda"></div>

<script>
  function listEvents(root) {
    var feed = root.feed;
    var entries = feed.entry || [];
    var html = ['<ul>'];

    for (var i = 0; i < entries.length; ++i) {
      var entry = entries[i];
      var title = (entry.title.type == 'html') ? entry.title.$t : escape(entry.title.$t);
      var start = (entry['gd$when']) ? entry['gd$when'][0].startTime : "";	

      html.push('<li>', start, ' ', title, '</li>');
    }

    html.push('</ul>');
    document.getElementById("agenda").innerHTML = html.join("");
  }
</script>

<script src="http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full?alt=json-in-script&callback=listEvents">
</script>

Mẫu

Để xem ví dụ thực hành về cách sử dụng JSON với API Dữ liệu của Google, hãy xem trang mẫu.

Tài nguyên khác

Bạn có thể muốn xem một số tài nguyên bên ngoài để tìm hiểu thêm về JSON và sử dụng JSON trong các ứng dụng web.

Trở lại đầu trang