Providing json responses for react-native app with Laravel - reactjs

I've been told that we have some limitations in front end side and we can't use the normal Eloquent json responses, instead I should prepare responses like:
[
{
"title": null,
"type": "animals",
"description": null,
"items": [
{
"type": "animal",
"content": {
"id": 31,
"image": null,
"name": "Asghar's dog",
"age": null,
"race": null,
"species_id": 1,
"reason": [
"Home"
]
}
}
]
},
{
"title": "Recommend",
"type": "recommendations",
"description": null,
"items": [
{
"type": "self_checks",
"content": {
"type": "prompt",
"title": "Self check for Asghar's dog.",
"description": "A short Self check.",
"cta_text": "Los geht’s"
}
},
{
"type": "worm_checks",
"content": {
"title": "Wurm-Vorsorge für Asghar's dog.",
"description": "Finde heraus, wie hoch das Wurm-Risiko deiner Fellnase ist.",
"cta_text": "Los geht’s",
"health_check_payload": {
"url": "https://****.de/check/worms?utm_term=Worms&utm_content=primer",
"title": "Wurm Check"
}
}
}
]
}
]
I need to know how should I structure my code to avoid code repetition and keep it clean. Also, I'm looking for any document regarding this type of responses.

Related

Mock service worker with openApi backend

I am working with MSW and OpenAPI-backend package.
I want to mock the booth browser server and test server.
I have OpenAPI definition available form with I generate generated.ts for RTK Query (out of scope for this question). I want to use OpenAPI spec to use it with OpenAPI Backend and generate MSW rest worker for browser and for test.
Setup is next:
index.tsx
import worker from './mocks/browser';
if (process.env.NODE_ENV === 'development') {
worker.start();
}
mock/browser.ts
import { setupWorker, rest } from 'msw';
import { OpenAPIBackend } from 'openapi-backend';
import type { Document } from 'openapi-backend';
import definition from './api.json';
// create our mock backend with openapi-backend
const api = new OpenAPIBackend({ definition: definition as Document });
api.register('notFound', (c, res, ctx) => res(ctx.status(404)));
api.registerHandler('notImplemented', async (c, req, res) => {
const { status, mock } = await api.mockResponseForOperation(
c.operation.operationId as string
);
return res.status(status).json(mock);
});
api.register('validationFail', (c, res, ctx) =>
res(ctx.status(400), ctx.json({ error: c.validation.errors }))
);
const worker = setupWorker(
rest.get('/*', (req) =>
api.handleRequest({
...req,
path: req.url.pathname,
headers: req.headers.all(),
method: req.method,
body: req.body,
})
)
);
export default worker;
api.JSON
{
"openapi": "3.0.1",
"info": {
"title": "Fetch API",
"description": "Source of truth for Fetch dashboard",
"version": "0.1.5"
},
"paths": {
"/config": {
"get": {
"tags": [
"Configuration"
],
"summary": "Retreive configuration object",
"description": "Returns configuration object (map) containing configuration parameters for UI (Map<String, String>)",
"responses": {
"200": {
"description": "successfull operation",
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"description": "Map serialized to json object.",
"example": {
"FA_COLOR": "red",
"FA_NAME": "fetch"
}
}
}
}
}
}
}
},
"/links": {
"get": {
"tags": [
"Notifications & Links",
"Walking Skeleton"
],
"summary": "List all defined links for hospital",
"description": "Retreives all defined links for hospital. Hospital ID is indirectly obtained from user identity.",
"responses": {
"200": {
"description": "successfull operation",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Link"
}
}
}
}
}
}
}
},
"/kpis": {
"get": {
"tags": [
"KPIS"
],
"summary": "List all KPIs for hospital(s) that current user is managing.",
"description": "Retreives all KPIs available for hospitals that current user is managing.",
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/KPI"
}
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"KPI": {
"type": "object",
"properties": {
"id": {
"type": "string",
"enum": [
"revenue",
"labour"
]
},
"hospital_id": {
"type": "string",
"description": "id of hospital that this KPI describes"
},
"goal": {
"type": "number",
"description": "full month goal"
},
"actual": {
"type": "number",
"description": "actual result"
},
"mtd_goal": {
"type": "number",
"description": "month to date goal, so that we can track projected fulfillment of goal."
},
"details": {
"type": "object",
"description": "Semi-structured way of describing details of calculation. Every KPI will potentialiy be described differently."
}
},
"required": [
"id",
"hospital_id",
"goal",
"actual",
"mtd_goal"
]
},
"Link": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "unique id of link"
},
"hospital_id": {
"type": "string",
"description": "id of hospital that this Link is configured for"
},
"title": {
"type": "string",
"description": "human readable title for URL"
},
"description": {
"type": "string",
"description": "Description of current link (alt text , or tooltip)"
},
"url": {
"type": "string",
"description": "Location of external resource"
},
"urgent": {
"type": "boolean",
"description": "Is urgency of notification elevated?"
},
"count": {
"type": "number",
"description": "Actual notification value. How many 'tasks' are waiting manager in external system."
},
"updated_at": {
"type": "integer",
"description": "Date/time of last notification update",
"format": "int64"
},
"children": {
"type": "array",
"description": "Since notifications are possibly presented in hierarchy all children of this notification will be gathered here",
"items": {
"$ref": "#/components/schemas/Link"
}
}
},
"required": [
"id",
"hospital_id",
"title",
"url"
],
"example": [
{
"id": 1,
"hospital_id": "001",
"title": "Link1",
"description": "description of Link1",
"url": "https://www.example.com/link1",
"urgent": true,
"count": 1,
"updated_at": 1631113184221,
"children": [
{
"id": 2,
"hospital_id": "001",
"title": "Link2",
"description": "description of Link2",
"url": "https://www.example.com/link2",
"urgent": true,
"count": 1,
"updated_at": 1631113184221
}
]
},
{
"id": 3,
"hospital_id": "002",
"title": "Link3",
"description": "description of Link3",
"url": "https://www.example.com/link3",
"urgent": false,
"count": 2,
"updated_at": 1631113184221
}
]
}
}
}
}
component.tsx
const { data: links, error, isLoading } = useGetLinksQuery({});
Which is fethcing localhost:3000/links
Error I am getting is:
mockServiceWorker.js:222 [MSW] Uncaught exception in the request handler for "GET http://localhost:3000/links":
Error: Unknown operation
at OpenAPIValidator.validateRequest (http://localhost:3000/static/js/vendors~main.chunk.js:63911:13)
at OpenAPIBackend.<anonymous> (http://localhost:3000/static/js/vendors~main.chunk.js:54246:45)
at async OpenAPIBackend.handleRequest (http://localhost:3000/static/js/vendors~main.chunk.js:54152:22)
This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses
getResponse # mockServiceWorker.js:222
async function (async)
getResponse # mockServiceWorker.js:175
handleRequest # mockServiceWorker.js:113
async function (async)
handleRequest # mockServiceWorker.js:112
(anonymous) # mockServiceWorker.js:271
Network tabs give:
Request URL: http://localhost:3000/links
Request Method: GET
Status Code: 500 (from service worker)
Referrer Policy: strict-origin-when-cross-origin
All related to article: https://dev.to/epilot/testing-react-with-jest-and-openapi-mocks-8gc
and https://testing-library.com/docs/react-testing-library/example-intro/
Thank you.
In your OpenApi u don't have any operationId.
You need to setup a unique Id by route.
{
"openapi": "3.0.1",
"info": {
"title": "Fetch API",
"description": "Source of truth for Fetch dashboard",
"version": "0.1.5"
},
"paths": {
"/config": {
"get": {
"tags": [
"Configuration"
],
"operationId": "config",
"summary": "Retreive configuration object",
"description": "Returns configuration object (map) containing configuration parameters for UI (Map<String, String>)",
"responses": {
"200": {
"description": "successfull operation",
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"description": "Map serialized to json object.",
"example": {
"FA_COLOR": "red",
"FA_NAME": "fetch"
}
}
}
}
}
}
}
},
"/links": {
"get": {
"tags": [
"Notifications & Links",
"Walking Skeleton"
],
"operationId": "links",
"summary": "List all defined links for hospital",
"description": "Retreives all defined links for hospital. Hospital ID is indirectly obtained from user identity.",
"responses": {
"200": {
"description": "successfull operation",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Link"
}
}
}
}
}
}
}
},
"/kpis": {
"get": {
"tags": [
"KPIS"
],
"summary": "List all KPIs for hospital(s) that current user is managing.",
"description": "Retreives all KPIs available for hospitals that current user is managing.",
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/KPI"
}
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"KPI": {
"type": "object",
"properties": {
"id": {
"type": "string",
"enum": [
"revenue",
"labour"
]
},
"hospital_id": {
"type": "string",
"description": "id of hospital that this KPI describes"
},
"goal": {
"type": "number",
"description": "full month goal"
},
"actual": {
"type": "number",
"description": "actual result"
},
"mtd_goal": {
"type": "number",
"description": "month to date goal, so that we can track projected fulfillment of goal."
},
"details": {
"type": "object",
"description": "Semi-structured way of describing details of calculation. Every KPI will potentialiy be described differently."
}
},
"required": [
"id",
"hospital_id",
"goal",
"actual",
"mtd_goal"
]
},
"Link": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "unique id of link"
},
"hospital_id": {
"type": "string",
"description": "id of hospital that this Link is configured for"
},
"title": {
"type": "string",
"description": "human readable title for URL"
},
"description": {
"type": "string",
"description": "Description of current link (alt text , or tooltip)"
},
"url": {
"type": "string",
"description": "Location of external resource"
},
"urgent": {
"type": "boolean",
"description": "Is urgency of notification elevated?"
},
"count": {
"type": "number",
"description": "Actual notification value. How many 'tasks' are waiting manager in external system."
},
"updated_at": {
"type": "integer",
"description": "Date/time of last notification update",
"format": "int64"
},
"children": {
"type": "array",
"description": "Since notifications are possibly presented in hierarchy all children of this notification will be gathered here",
"items": {
"$ref": "#/components/schemas/Link"
}
}
},
"required": [
"id",
"hospital_id",
"title",
"url"
],
"example": [
{
"id": 1,
"hospital_id": "001",
"title": "Link1",
"description": "description of Link1",
"url": "https://www.example.com/link1",
"urgent": true,
"count": 1,
"updated_at": 1631113184221,
"children": [
{
"id": 2,
"hospital_id": "001",
"title": "Link2",
"description": "description of Link2",
"url": "https://www.example.com/link2",
"urgent": true,
"count": 1,
"updated_at": 1631113184221
}
]
},
{
"id": 3,
"hospital_id": "002",
"title": "Link3",
"description": "description of Link3",
"url": "https://www.example.com/link3",
"urgent": false,
"count": 2,
"updated_at": 1631113184221
}
]
}
}
}
}

Parse this Json array and extract the value of text

Here is the full json that I want to parse and extract the text that has the value: The product is in second line 3rd row.
Can someone help?
"activities": [
{
"type": "message",
"id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"timestamp": "2019-07-01T15:18:56.8251462Z",
"serviceUrl": "XXXXXXXXXXXXXXXXXXXXXXXXX",
"channelId": "directline",
"from": {
"id": "user1"
},
"conversation": {
"id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
},
"text": "the milk"
},
{
"type": "message",
"id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"timestamp": "2019-07-01T15:18:57.6856172Z",
"localTimestamp": "2019-07-01T15:18:57.5099359+00:00",
"channelId": "directline",
"from": {
"id": "XXXXXX",
"name": "XXXXXX"
},
"conversation": {
"id": "XXXXXXXXXXXXXXXXXX"
},
"text": "The product is in second line 3rd row",
"attachments": [],
"entities": [],
"replyToId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
],
"watermark": "1"
}
You have specified that this is a full json you have placed in the question, But it is not full json you are missing something.
"activities":
[ //json array start from here
{
"type": "message",
"id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"timestamp": "2019-07-01T15:18:56.8251462Z",
"serviceUrl": "XXXXXXXXXXXXXXXXXXXXXXXXX",
"channelId": "directline",
"from": {
"id": "user1"
},
"conversation": {
"id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
},
"text": "the milk"
},
{
"type": "message",
"id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"timestamp": "2019-07-01T15:18:57.6856172Z",
"localTimestamp": "2019-07-01T15:18:57.5099359+00:00",
"channelId": "directline",
"from": {
"id": "XXXXXX",
"name": "XXXXXX"
},
"conversation": {
"id": "XXXXXXXXXXXXXXXXXX"
},
"text": "The product is in second line 3rd row",
"attachments": [],
"entities": [],
"replyToId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
], //json array ends here
these are extra lines
***"watermark": "1"
}***
if you want to use this array you need to add a '{' in very top line before
"activities": [
I am placing here a valid json now you can check it on Json parser used to parse json in objects
*Valid Json Here : *
{
"activities": [
{
"type": "message",
"id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"timestamp": "2019-07-01T15:18:56.8251462Z",
"serviceUrl": "XXXXXXXXXXXXXXXXXXXXXXXXX",
"channelId": "directline",
"from": {
"id": "user1"
},
"conversation": {
"id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
},
"text": "the milk"
},
{
"type": "message",
"id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"timestamp": "2019-07-01T15:18:57.6856172Z",
"localTimestamp": "2019-07-01T15:18:57.5099359+00:00",
"channelId": "directline",
"from": {
"id": "XXXXXX",
"name": "XXXXXX"
},
"conversation": {
"id": "XXXXXXXXXXXXXXXXXX"
},
"text": "The product is in second line 3rd row",
"attachments": [],
"entities": [],
"replyToId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
],
"watermark": "1"
}

Json schema for array of objects doesn't validate

I have this schema for a json response
{
"title": "Products",
"description": "schema for products",
"type": "array",
"properties": {
"id": {
"description": "id of a product",
"type": "integer"
},
"name": {
"description": "name of the product",
"type": "string"
},
"created_at": {
"description": "record created_at",
"type": "string",
"format": "date-time"
},
"updated_at": {
"description": "record updated_at",
"type": "string",
"format": "date-time"
}
},
"required": ["id", "name"]
}
and I want to match this schema with this json
[{
"id": 1,
"name": "Cricket Ball"
}, {
"id": 2,
"name": "Soccer Ball"
}, {
"id": 3,
"name": "football ball"
}, {
"id": 4,
"name": "Basketball ball"
}, {
"id": 5,
"name": "Table Tennis ball"
}, {
"id": 6,
"name": "Tennis ball"
}]
This schema matches the response but it also matches the schema in which the required field is this
"required": ["ids", "names"]
I think the schema is validated against the array and the objects in the array are not validated.
The way you have it set up now, your properties key refers to the array itself, not to each item, and is being ignored (because arrays don't have properties, they just have items). You need to use the items key to validate each item in the array, like so:
{
"title": "Products",
"description": "schema for products",
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"description": "id of a product",
"type": "integer"
},
"name": {
"description": "name of the product",
"type": "string"
},
"created_at": {
"description": "record created_at",
"type": "string",
"format": "date-time"
},
"updated_at": {
"description": "record updated_at",
"type": "string",
"format": "date-time"
}
},
"required": ["id", "name"]
}
}
try map
new_array = response.map{ |k| { 'id': k['properties']['id']['description'], 'name': k['properties']['name']['description'] } }

Sorting arrays in Mongo

H have json document with array. As I can't add to beginning of array with push or addtoset I need to sort array. Example
{
"Component": [
{
"Id": "PDP-1",
"Links": {"Link": [
{
"Text": "Western Division",
"Url": "/1x7-en70ai/last-minute-holidays-western-division",
"Title": "Last minute holidays Western Division"
},
{
"Text": "Browse Regions ",
"Url": "/1x7-en6uly-10ts/last-minute-holidays-gambia/regions",
"Title": "Last minute holidays Gambia",
"Style": "BrowseForMore"
},
{
"Text": "City of Banjul",
"Url": "/1x6-en6vq7/holidays-city-of-banjul",
"Title": "City of Banjul Holidays"
},
{
"Text": "Western Division",
"Url": "/1x6-en70ai/holidays-western-division",
"Title": "Western Division Holidays"
}
]},
"Title": "Regions",
"Type": "PDP"
},
{
"Id": "PDP-2",
"Links": {"Link": [
{
"Text": "Bijilo",
"Url": "/1x7-enbmy6/last-minute-holidays-bijilo",
"Title": "Last minute holidays Bijilo"
},
{
"Text": "Browse Cities ",
"Url": "/1x7-en6uly-10tt/last-minute-holidays-gambia/cities",
"Title": "Last minute holidays Gambia",
"Style": "BrowseForMore"
},
{
"Text": "Banjul Beach",
"Url": "/1x6-enakgm/holidays-banjul-beach",
"Title": "Banjul Beach Holidays"
},
{
"Text": "Bijilo",
"Url": "/1x6-enbmy6/holidays-bijilo",
"Title": "Bijilo Holidays"
},
{
"Text": "Brufut Heights",
"Url": "/1x6-encok8/holidays-brufut-heights",
"Title": "Brufut Heights Holidays"
},
{
"Text": "Kololi",
"Url": "/1x6-enpnle/holidays-kololi",
"Title": "Kololi Holidays"
},
{
"Text": "Kotu",
"Url": "/1x6-enq067/holidays-kotu",
"Title": "Kotu Holidays"
}
]},
"Title": "Cities",
"Type": "PDP"
}
],
"Id": "118431",
"Template": {
"PageTemplate": {
"Code": "2B2",
"text": "041 - TEMP2 - COP_CONCOU_{LAST MINUTE}"
},
"Category": {
"Code": "1X7",
"Type": "Product",
"text": "Last minute holidays"
},
"GeoObject": {
"Code": "EN6ULY",
"text": "Gambia, The"
},
"GeoObjectType": {
"Code": "1A",
"text": "Political"
},
"GeoObjectSubType": {
"Code": "10TR",
"text": "Country"
}
},
"Type": "Content",
"Url": "/1x7-en6uly/last-minute-holidays-gambia",
"_id": {"$oid": "528492d4c90fa9fcd0436929"}
}
I want to sort this by Style in Links.Link 'BrowseForMore'. Any idea how to do it? I thought I could add dummy array with push which could then sort it the way I want. Any help appreciated
You appear to want to update the array and keep the sort order with your Links.Link.Style value at the front of the list. In which case use the $sort modifier with update.
db.collection.update(
{ _id: id },
{ $push: { "Links.Link: {$each: [doc], $sort { Style: -1 }}} }
)
The $each operator is required even if there is only one document, but can take many.
if you are trying to use $addToSet to maintain unique documents the official MongoDB line is that sets are considered to be unordered and hence the modifiers are not available here.

Use a for-in loop to get data from a JSON object which is not an array

I'm trying to loop through the results of a JSON response and get the title of each article, however my hosting company mentioned the returned object is not an array, so I can't loop through the articles.
Currently it gives me an undefined on the length of the amount of articles.
How can I loop through the articles and get their titles?
I tried everything below, and finally read somewhere I could use a for-in loop.
So I was checking out this example here: http://www.w3schools.com/js/tryit.asp?filename=tryjs_object_for_in
However, I have no idea how to apply this loop on my data to get just the articles and then loop through these and get their properties.
JSON RESPONSE
{
"blog": {
"id": "1464",
"comments": true,
"url": "blogs\/magazine",
"rss": "blogs\/magazine.rss",
"title": "Taj Magazine",
"articles": {
"3748": {
"id": 3748,
"image": 7442452,
"url": "blogs\/magazine\/foodies-walhalla-2",
"title": "Foodies Walhalla 2",
"author": "",
"author_url": false,
"summary": "dit is de samenvatting tekst",
"content": "dit is het hele artikel",
"date": "2013-11-13 13:54:00",
"comments": [],
"comments_count": 0,
"tags": {
"foodies-walhalla": {
"id": "9794",
"url": "blogs\/magazine\/tagged\/foodies-walhalla",
"title": "Foodies Walhalla",
"count": "2"
},
"magazine": {
"id": "9744",
"url": "blogs\/magazine\/tagged\/magazine",
"title": "magazine",
"count": "6"
}
}
},
"3747": {
"id": 3747,
"image": 7442441,
"url": "blogs\/magazine\/foodies-walhalla-1",
"title": "Foodies Walhalla 1",
"author": "",
"author_url": false,
"summary": "f df gdsfg",
"content": "dsfgsdfgdf sdfg",
"date": "2013-11-13 11:22:00",
"comments": [],
"comments_count": 0,
"tags": {
"foodies-walhalla": {
"id": "9794",
"url": "blogs\/magazine\/tagged\/foodies-walhalla",
"title": "Foodies Walhalla",
"count": "2"
},
"magazine": {
"id": "9744",
"url": "blogs\/magazine\/tagged\/magazine",
"title": "magazine",
"count": "6"
}
}
},
"3744": {
"id": 3744,
"image": 7442425,
"url": "blogs\/magazine\/beauty-artikel-2",
"title": "Beauty artikel 2",
"author": "",
"author_url": false,
"summary": "beauty article 2",
"content": "dfg sfg sdfg sdfgd gdsf df gsdf gdsf g",
"date": "2013-11-13 11:21:00",
"comments": [],
"comments_count": 0,
"tags": {
"beauty": {
"id": "9792",
"url": "blogs\/magazine\/tagged\/beauty",
"title": "beauty",
"count": "2"
},
"healthy": {
"id": "9745",
"url": "blogs\/magazine\/tagged\/healthy",
"title": "healthy",
"count": "2"
},
"magazine": {
"id": "9744",
"url": "blogs\/magazine\/tagged\/magazine",
"title": "magazine",
"count": "6"
}
}
},
"3745": {
"id": 3745,
"image": 7442417,
"url": "blogs\/magazine\/love-life-1",
"title": "Love & Life 1",
"author": "",
"author_url": false,
"summary": "dfgdsfgd",
"content": "f gdf gdfgdfg dfgdsfgdsfgdsfg",
"date": "2013-11-13 11:21:00",
"comments": [],
"comments_count": 0,
"tags": {
"love-life": {
"id": "9793",
"url": "blogs\/magazine\/tagged\/love-life",
"title": "love & life",
"count": "2"
},
"magazine": {
"id": "9744",
"url": "blogs\/magazine\/tagged\/magazine",
"title": "magazine",
"count": "6"
}
}
},
"3746": {
"id": 3746,
"image": 7442388,
"url": "blogs\/magazine\/love-life-2",
"title": "Love & Life 2",
"author": "",
"author_url": false,
"summary": "dfkjghksdjfh gdskfjdj sdlkjfhdjfghdjklfsdfkjhg df gd ghdkjsfhgkjsd fg lkjdshklgdfh kjds glkjsdh kljdsfh",
"content": "dfkjghksdjfh gdskfjdj sdlkjfhdjfghdjklfsdfkjhg df gd ghdkjsfhgkjsd fg lkjdshklgdfh kjds glkjsdh kljdsfh",
"date": "2013-11-13 11:21:00",
"comments": [],
"comments_count": 0,
"tags": {
"love-life": {
"id": "9793",
"url": "blogs\/magazine\/tagged\/love-life",
"title": "love & life",
"count": "2"
},
"magazine": {
"id": "9744",
"url": "blogs\/magazine\/tagged\/magazine",
"title": "magazine",
"count": "6"
}
}
}
}
},
"request": {
"url": "http:\/\/taj-ringen.webshopapp.com\/blogs\/magazine\/?format=json",
"method": "get",
"ssl": false,
"get": {
"format": "json"
},
"post": [],
"device": {
"platform": "windows",
"type": "webkit",
"mobile": false
}
},
"template": "pages\/blog.rain",
"renderer": "json"
}
JAVASCRIPT
<div id="loadstatus"></div>
<script type="text/javascript" language="javascript">
var newresult = '';
$.ajax({
type: "GET",
url: "http://taj-ringen.webshopapp.com/blogs/magazine/?format=json",
data: "",
dataType: "json",
success: function (mydata) {
console.log('load successful');
console.log('mydata.blog.articles.length: ' + mydata.blog.articles.length); //'undefined' error
for (var i = 0; i < mydata.blog.articles.length; i++) {
newresult += mydata.blog.articles[i].title;
}
}
});
</script>
I also had a look at this post: Convert Object to JSON string
tried the jQuery.parseJSON function
console.log(mydata);
var tmp = jQuery.parseJSON(mydata);
console.log(tmp);
console.log('tmp.blog.articles.length: ' + tmp.blog.articles.length);
But there I get an error Uncaught SyntaxError: Unexpected token o on line jquery-1.10.2.min.js:4
tried the $.map function
var array = $.map(mydata, function (e) {
return [$.map(e, function (v) {
return v;
})];
});
console.log(array);
console.log('tmp.blog.articles.length: ' + array.blog.articles.length);
Here I get Uncaught TypeError: Cannot use 'in' operator to search for '14' in pages/blog.rain on line jquery-1.10.2.min.js:4
What I'm trying to to is convert the object that is returned by the site and be able to loop through it.
Iterate through the article object, pulling out the keys associated with each article using the method described in the below post:
How to list the properties of a JavaScript object
You could also use the following loop:
for(var article in blog.articles) {
console.log(blog.articles[article].title);
}

Resources