This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
hello maybe stupid question but how can i print for example start out of this
var text = {
"responseData": {
"results": [
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://dojotoolkit.org/",
"url": "http://dojotoolkit.org/",
"visibleUrl": "dojotoolkit.org",
"cacheUrl": "http://www.google.com/search?q=cache:sUiWYphwkaoJ:dojotoolkit.org",
"title": "Unbeatable JavaScript Tools - The <b>Dojo Toolkit</b>",
"titleNoFormatting": "Unbeatable JavaScript Tools - The Dojo Toolkit",
"content": "<b>Dojo</b> saves you time, delivers powerful performance, and scales with your development process. It's the <b>toolkit</b> experienced developers turn to for building <b>...</b>"
},
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://dojotoolkit.org/download/",
"url": "http://dojotoolkit.org/download/",
"visibleUrl": "dojotoolkit.org",
"cacheUrl": "http://www.google.com/search?q=cache:cQhx_NOJhyYJ:dojotoolkit.org",
"title": "Download - The <b>Dojo Toolkit</b>",
"titleNoFormatting": "Download - The Dojo Toolkit",
"content": "This download is ideal for situations where a custom build will not be required."
},
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://dojotoolkit.org/documentation/",
"url": "http://dojotoolkit.org/documentation/",
"visibleUrl": "dojotoolkit.org",
"cacheUrl": "http://www.google.com/search?q=cache:ws95YbyVgxgJ:dojotoolkit.org",
"title": "Documentation - The <b>Dojo Toolkit</b>",
"titleNoFormatting": "Documentation - The Dojo Toolkit",
"content": "How do I start learning Dojo? Where are the docs? How do I get support and <b>...</b>"
},
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://en.wikipedia.org/wiki/Dojo_Toolkit",
"url": "http://en.wikipedia.org/wiki/Dojo_Toolkit",
"visibleUrl": "en.wikipedia.org",
"cacheUrl": "http://www.google.com/search?q=cache:6gxw4t2myDIJ:en.wikipedia.org",
"title": "<b>Dojo Toolkit</b> - Wikipedia, the free encyclopedia",
"titleNoFormatting": "Dojo Toolkit - Wikipedia, the free encyclopedia",
"content": "<b>Dojo Toolkit</b> (stylized as dōjō toolkit) is an open source modular JavaScript library (or more specifically JavaScript toolkit) designed to ease the rapid <b>...</b>"
}
],
"cursor": {
"resultCount": "83,500",
"pages": [
{
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
},
{
"start": "8",
"label": 3
},
{
"start": "12",
"label": 4
},
{
"start": "16",
"label": 5
},
{
"start": "20",
"label": 6
},
{
"start": "24",
"label": 7
},
{
"start": "28",
"label": 8
}
],
"estimatedResultCount": "83500",
"currentPageIndex": 0,
"moreResultsUrl": "http://www.google.com/search?oe=utf8&ie=utf8&source=uds&start=0&hl=en&q=dojo+toolkit",
"searchResultTime": "0.20"
}
},
"responseDetails": null,
"responseStatus": 200
}
I have problem with accessing object in object. Can u please provide me some information?
i wanted to do something like :
alert(text.responseData['results'])
Thank you
Paste this text json object in chrome's console. And try accessing text variable. It will auto complete and help you find the path to the objects inside the variable, you desire. That's what I do to json objects. For your start variable try this code.
var pages = text.responseData.cursor.pages;
for(var i=0; i < pages.length; i++){
console.log(pages[i].start)
}
Related
Ember uses Restadapter & Jsonapiadapter for the adapters.
What are the exact differences between the 2 in terms of data formats for request/response ?
Any other things we need to ensure when using any of these 2.
The JSONAPIAdapter conforms to the JSONApi spec
Use RESTAdapter when you have an JSON API that follows a REST endpoint with pluralized object names and has a root node using the name of the object being returned.
Examples below:
Example JSONAPI spec object:
{
"data": [{
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON API paints my bikeshed!"
},
"relationships": {
"author": {
"links": {
"self": "http://example.com/articles/1/relationships/author",
"related": "http://example.com/articles/1/author"
},
"data": { "type": "people", "id": "7" }
}
},
}],
"included": [{
"type": "people",
"id": "7",
"attributes": {
"name": "Dave",
"twitter": "kiwiupover"
}
}]
}
Example Rest json api object:
{
"posts": {
"id": 5,
"title": "An API that gets bikeshed for months ",
"author": "kiwiupover",
"comments": [1]
},
"comments": [{
"id": 1,
"name": "Dave",
}]
}
Ember Data provides straightforward methods for adapting your DS.adapter to your specific JSON API shape.
There is a third adapter from which the previously mentioned adapters are extended from.
I don't understand why I am getting NaN. Is there something I am missing, could be the object, or my code ?
$(document).ready(function() {
var text = {
"kind": "books#volume",
"id": "Wfan6L9RGgYC",
"etag": "UlsLzySUlh0",
"selfLink": "https://www.googleapis.com/books/v1/volumes/Wfan6L9RGgYC",
"volumeInfo": {
"title": "The Modern Web",
"subtitle": "Multi-device Web Development with HTML5, CSS3, and JavaScript",
"": [
"Peter Gasston"
],
"publisher": "No Starch Press",
"publishedDate": "2013",
"description": "<p><b>A Guide to Modern Web Development</b><br></p><p>Today's web technologies are evolving at near-light speed, bringing the promise of a seamless Internet ever closer to reality. When users can browse the Web on a three-inch phone screen as easily as on a fifty-inch HDTV, what's a developer to do?</p><p>Peter Gasston's <i>The Modern Web</i> will guide you through the latest and most important tools of device-agnostic web development, including HTML5, CSS3, and JavaScript. His plain-English explanations and practical examples emphasize the techniques, principles, and practices that you'll need to easily transcend individual browser quirks and stay relevant as these technologies are updated.</p><p>Learn how to:</p><p>* Plan your content so that it displays fluidly across multiple devices<br>* Design websites to interact with devices using the most up-to-date APIs, including Geolocation, Orientation, and Web Storage<br>* Incorporate cross-platform audio and video without using troublesome plug-ins<br>* Make images and graphics scalable on high-resolution devices with SVGUse powerful HTML5 elements to design better forms</p><p>Turn outdated websites into flexible, user-friendly ones that take full advantage of the unique capabilities of any device or browser. With the help of <i>The Modern Web</i>, you'll be ready to navigate the front lines of device-independent development.</p>",
"industryIdentifiers": [{
"type": "ISBN_10",
"identifier": "1593274874"
}, {
"type": "ISBN_13",
"identifier": "9781593274870"
}],
"readingModes": {
"text": true,
"image": true
},
"pageCount": 264,
"printedPageCount": 266,
"dimensions": {
"height": "24.00 cm",
"width": "17.80 cm",
"thickness": "1.50 cm"
},
"printType": "BOOK",
"categories": [
"Computers / Software Development & Engineering / General",
"Computers / Web / Design"
],
"averageRating": 4.5,
"ratingsCount": 3,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": true,
"contentVersion": "1.2.2.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=Wfan6L9RGgYC&printsec=frontcover&img=1&zoom=5&edge=curl&imgtk=AFLRE72KO7jCxe5uWt_wdrgHfdSNO_raoAKYbPNaAILa300r3DxeVHIqEeZto77JClWzw41ZwwbcMlVl2Ki9dF_ycIEUDhwbetDSF6K112O_XoebMDRoRNA5vskWyCtpGig-LaVPbE7j&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=Wfan6L9RGgYC&printsec=frontcover&img=1&zoom=1&edge=curl&imgtk=AFLRE70to3PUyJeiv-brcBCzs330NDwRGM4cYu9gHzdVNLrIEn7ghBo5Gms9MAFxQ8ZkRt0-JZhCJq7T0V_vOLwMhDu4f_2icMtDrO5bMPSqRa4EuB9-3XGaNH-UxsYBvJIMUadwdd4Y&source=gbs_api",
"small": "http://books.google.com/books/content?id=Wfan6L9RGgYC&printsec=frontcover&img=1&zoom=2&edge=curl&imgtk=AFLRE709uVhXoOlgZxdwB4DKF0X1zVPvV7_4EA_PvhNlIGLKknTSsZiIoDnsJPsswWKBQIoSC-gJ0vOe_4kTiWPU38xZydOliDp5u0SxJqqFbDIKnz-KxprkLg7Ze2fxJWGBXRQSgHJA&source=gbs_api",
"medium": "http://books.google.com/books/content?id=Wfan6L9RGgYC&printsec=frontcover&img=1&zoom=3&edge=curl&imgtk=AFLRE72idQ0vc5gY408WHZTWFY8AOQLhGVbI4ktB4O6NXQFbbHY0VrM0PJWA_XF_98_NThQtP8tvw73qpSwqkGoi-QKzMPfi_M75VzK-zbxVsFZ_rtfeMGHWREhGACvV-F39BhQ1WXwt&source=gbs_api",
"large": "http://books.google.com/books/content?id=Wfan6L9RGgYC&printsec=frontcover&img=1&zoom=4&edge=curl&imgtk=AFLRE73M-PJZ0bTkffdLAwU427ppNpxsenoBSi91ABnrm4lNMPwOBNDIL23OTK7ZNvGlGChk9klXAP3DDoQbLXPwct-F_m9j1KKJ4w77HkeP69-eYdwxW1Z5iNgVYqyZCRj3AkAHmOaZ&source=gbs_api",
"extraLarge": "http://books.google.com/books/content?id=Wfan6L9RGgYC&printsec=frontcover&img=1&zoom=6&edge=curl&imgtk=AFLRE70yPdCZ5tbR5aL9WbnodE4Uf263MR_bPekV6tab5QKe193uKXqXqilaTmc-bByqZGmaEk38KBic64e-dp8VON30C-E7eJP-TR-6cjVA3dmVTARYkMGMiE5dQsPsMGO2z_6p4ryx&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.com/books?id=Wfan6L9RGgYC&hl=&source=gbs_api",
"infoLink": "http://books.google.com/books?id=Wfan6L9RGgYC&hl=&source=gbs_api",
"canonicalVolumeLink": "http://books.google.com/books/about/The_Modern_Web.html?hl=&id=Wfan6L9RGgYC"
},
"layerInfo": {
"layers": [{
"layerId": "geo",
"volumeAnnotationsVersion": "8"
}]
},
"saleInfo": {
"country": "US",
"saleability": "FOR_SALE",
"isEbook": true,
"listPrice": {
"amount": 27.95,
"currencyCode": "USD"
},
"retailPrice": {
"amount": 15.37,
"currencyCode": "USD"
},
"buyLink": "http://books.google.com/books?id=Wfan6L9RGgYC&hl=&buy=&source=gbs_api",
"offers": [{
"finskyOfferType": 1,
"listPrice": {
"amountInMicros": 27950000,
"currencyCode": "USD"
},
"retailPrice": {
"amountInMicros": 15370000,
"currencyCode": "USD"
},
"giftable": true
}]
},
"accessInfo": {
"country": "US",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true
},
"pdf": {
"isAvailable": true
},
"webReaderLink": "http://books.google.com/books/reader?id=Wfan6L9RGgYC&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
}
}
$.each(text, function(i, value) {
$('</p>').appendTo("#container").text(text[i].title + text[i].subtitle);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
Your $.each function is looping through every property at the root of your object, and the way your object is structured, not every property has a nested title or subtitle property.
You would either have to structure your object consistently, or check for the properties you need before you try to access them.
Question:
Is there a plain or native javascript way to validate a JSON script against a JSON schema?
I have found lots of libraries on Github, but no native/plain solution. Does EcmaScript not have a specification for this? and do none of the browsers (or nodejs) have a way to validate JSON natively?
Context of Question:
I have a very complex schema that I developed.
It is supposed to work along with a script that requires that the JSON data passed into it to comply with the schema.
Simply, no.
There was something called JSON Schema, which was an Internet Draft which expired in 2013. Internet Drafts are the first stage to producing an Internet Standard. See more about it at the official site, as it seems to potentially still be actively developed, although it is not (to my knowledge) in widespread use.
An example of the schema:
{
"$schema": "http://json-schema.org/schema#",
"title": "Product",
"type": "object",
"required": ["id", "name", "price"],
"properties": {
"id": {
"type": "number",
"description": "Product identifier"
},
"name": {
"type": "string",
"description": "Name of the product"
},
"price": {
"type": "number",
"minimum": 0
},
"tags": {
"type": "array",
"items": {
"type": "string"
}
},
"stock": {
"type": "object",
"properties": {
"warehouse": {
"type": "number"
},
"retail": {
"type": "number"
}
}
}
}
}
will validate this example JSON:
{
"id": 1,
"name": "Foo",
"price": 123,
"tags": [
"Bar",
"Eek"
],
"stock": {
"warehouse": 300,
"retail": 20
}
}
There seems to be at least one pure JS solution now (https://github.com/tdegrunt/jsonschema) available via npm (https://www.npmjs.com/package/jsonschema). I am not a contributor, although I appreciate their work.
I'm new to Ember and from what I understand it has a very specific way it excepts its json api response to look like. Like so:
{
"post": {
"id": 1,
"title": "Node is not omakase",
"comments": [1, 2, 3]
},
"comments": [{
"id": 1,
"body": "But is it _lightweight_ omakase?"
},
{
"id": 2,
"body": "I for one welcome our new omakase overlords"
},
{
"id": 3,
"body": "Put me on the fast track to a delicious dinner"
}]
}
Now the api I've already built has an json response that looks like so:
{
"data": {
"id": 1,
"name": "Pansy Bednar",
"links": [
{
"rel": "self",
"uri": "/pansy-bednar15"
}
],
"players": {
"data": [
{
"id": 2,
"name": "Nicholas O'Reilly",
"position": "cad",
"age": 23,
"value": "640",
"links": [
{
"rel": "self",
"uri": "/team/nicholas-o-reilly71"
}
]
}
]
}
}
}
The api is pretty big and is working fine with the mobile app. So a code re write would be to costly I would just choose another js framework even though I like Ember the best.
So my question is is there any way I can adapt the expected json response in ember. If yes how hard is it? Worth the time or should I just go for Angular or Aurelia.
or am I completely wrong and there is no one expected response to ember?
The thing you can do with ember is to write your very own adapter for this there are already many questions+answers out there:
https://stackoverflow.com/a/17938593/1581725
https://stackoverflow.com/a/24411550/1581725
...
And there is also this blog entry here: http://eviltrout.com/2013/03/23/ember-without-data.html it's about using ember without ember-data.
Found this little gem called normalizePayload - maybe this would also work for your case: https://stackoverflow.com/a/21790093/1581725
This question already has an answer here:
Get length of a JavaScript array [duplicate]
(1 answer)
Closed 8 years ago.
I have the following data source -- converted to JSON using to XML using X2JS:
{
"blog": {
"article": [
{
"id": "1",
"author": "eat-sleep-code",
"title": {
"__cdata": "Thefirstarticle."
},
"content": {
"__cdata": "\nThisismyfirstarticleinmytestsite.\n"
},
"createdate": "2014-05-09"
},
{
"id": "2",
"author": "eat-sleep-code",
"title": {
"__cdata": "Thesecondarticle."
},
"content": {
"__cdata": "\nThisismysecondarticleinmytestsite.Thisarticle'screatedateisactuallyearlier.\n"
},
"createdate": "2014-05-08"
}
]
}
}
I am trying to find the number of "articles".
Object.keys(jsonObject).length; just gets me 1. I am guessing because it is finding one "blog" item.
jsonObject.blog.article.length