multiple returned keys json - javascript

I have a joomla site running k2 and pulling info from it by adding format=json to the end of the string: https://www.example.com/posts?format=json which outputs something like this:
{
site: {
url: "https://www.example.com",
name: "mySite"
},
category: {
id: "67",
name: "Gauteng",
alias: "gauteng",
link: "/tna/provincial/gauteng.html",
parent: "66",
extraFieldsGroup: "0",
image: null,
ordering: "1",
events: {
K2CategoryDisplay: ""
},
chidlren: []
},
items: [{
id="1",
title="The Title",
body="body content here..."
},
{
id="2",
title="The Title",
body="body content here..."
}
}
now i am creating a service for this and just want to access "items".
.factory('Posts', function($http) {
var posts = [];
return {
getPosts: function(){
return $http.get("https://www.example.com/posts?format=json").then(function(response){
posts = response;
return posts;
});
},
getPost: function(index){
return posts[index];
}
}
});
it doesnt seem to be working though. is there any way to access just "items" with the call?

You post syntax should be posts = response.data.items
return $http.get("https://www.example.com/posts?format=json").then(function(response){
posts = response.data.items; //items here
return posts;
});

Related

Get data from RichSnippet JSON and set the same string into other variable

I have this JSON generated from external (Reviews-io) script:
https://widget.reviews.co.uk/rich-snippet/dist.js
richSnippet({
store: "www.storedigital.local",
sku:"6647;6647_5;6647_4;6647_3;6647_11;6647_10;6647_2;6647_1;6647_9;6647_8;6647_7;6647_6",
data:{
"url": "store.stg.gsd.local/1/silla-replica-eames.html",
"description": ``,
"mpn": "6647",
"offers" :[{
"#type":"Offer",
"availability": "http://schema.org/InStock",
"price": "559",
"priceCurrency": "MXN",
"url": "https://store.stg.gsd.localx/1/silla-replica-eames.html",
"priceValidUntil": "2022-05-26",
}],
"brand": {
"#type": "Brand",
"name": "Not Available",
}
}
})
I need to get all the string of numbers in "sku", and then put them in another variable as same format (6647; 6647_1; 6647_2)
I try to get the numbers using this JS but doesn't works
var skucollection = JSON.parse(richSnippet, function (key, value) {
if (key == "sku") {
return new Sku(value);
} else {
return value;
}
});
Can you help me check what I am doing wrong, to get this sku's value string, please?
JSON.parse is not too much? ,handle it as it is internally (a JSON indeed)
var richSnippet = {
store: 'www.storedigital.local',
sku: '6647;6647_5;6647_4;6647_3;6647_11;6647_10;6647_2;6647_1;6647_9;6647_8;6647_7;6647_6',
algomas: [],
data: {
url: 'store.stg.gsd.local/1/silla-replica-eames.html',
description: ``,
mpn: '6647',
offers: [
{
'#type': 'Offer',
availability: 'http://schema.org/InStock',
price: '559',
priceCurrency: 'MXN',
url: 'https://store.stg.gsd.localx/1/silla-replica-eames.html',
priceValidUntil: '2022-05-26',
},
],
brand: {
'#type': 'Brand',
name: 'Not Available',
},
},
};
var test;
Object.keys(richSnippet).forEach((key) => {
if (key == 'sku') {
test = richSnippet[key];
}
});
console.log('test', test);

Next.js: getStaticPaths for nested dynamic routes

Imagine you have this data structure:
const data = {
posts: [{
id: 1,
title: "Post 1"
slug: "post-1"
}, {
id: 2,
title: "Post 2"
slug: "post-2"
}],
comments: [{
id: 1,
postId: "post-1",
text: "Comment 1 for Post 1"
}, {
id: 2,
postId: "post-1",
text: "Comment 2 for Post 1"
}, {
id: 3,
postId: "post-2",
text: "Comment 1 for Post 2"
}]
}
An you have the following route /posts/[postId[/[commentId]
so the Next.js structure folder is: posts/[postId]/[commented].js
Then you need to generate the static paths for this routes.
I'm coded the following:
export async function getStaticPaths() {
const { posts, comments } = data
const paths = posts.map((post) => {
return comments
.filter((comment) => comment.postId === post.slug)
.map((comment) => {
return {
params: {
postId: post.slug,
commentId: comment.id
}
}
})
})
}
But it's not working. The throwed error was:
Error: Additional keys were returned from `getStaticPaths` in page "/clases/[courseId]/[lessonId]". URL Parameters intended for this dynamic route must be nested under the `params` key, i.e.:
return { params: { postId: ..., commentId: ... } }
Keys that need to be moved: 0, 1.
How I can "map" or "loop" the data to a proper returned format?
Thanks in advance!
The problem seems to be that your returning this from getStaticPaths data with a wrong shape:
[
[ { params: {} }, { params: {} } ],
[ { params: {} } ]
]
The correct shape is:
[
{ params: {} },
{ params: {} },
{ params: {} }
]
Just tried this and it works.
export async function getStaticPaths() {
const paths = data.comments.map((comment) => {
return {
params: {
postId: comment.postId,
commentId: comment.id
}
}
});
console.log(paths);
return {
paths,
fallback: false
}
};
It generates 3 urls:
/posts/post-1/1
/posts/post-1/2
/posts/post-2/3
Is that what you need?
Like mention #Aaron the problem is for double array of filter y el map.
return {
paths: [
{ params: { id: '1' } },
{ params: { id: '2' } }
],
fallback: ...
}
Doc 📚 ➡ https://nextjs.org/docs/basic-features/data-fetching#the-paths-key-required

JSON data not being displayed in angularjs ui-grid

I'm new to AngularJS and so far haven't had any problems until this one...
I am trying to display json data returned for my REST service call without any luck. I can hard-code in a data array into my controller script file and that will be displayed on my web page just fine however when trying to display my json data I'm not having any luck.
This is what I currently have coded...
Web page-
<div ng-controller="ExceptionLogDataController">
<div ui-grid="gridOptions" class="vertexGrid"></div>
</div>
ExceptionLogDataController-
$scope.vertexData = [];
$scope.gridOptions = {
enableSorting: true,
data: "vertexData",
columnDefs: [
{ name: 'Data Id', field: 'DataId' },
{ name: 'Source Date Time', field: 'SourceDateTime' },
{ name: 'Message Text', field: 'MessageText' },
{ name: 'IsDirty', field: 'IsDirty' }
// { name: 'FileName', field: 'FileName' },
// { name: 'GenJIRATicket', field: 'GenJIRATicket' },
// { name: 'MessageCount', field: 'MessageCount' },
// { name: 'MachineName', field: 'MachineName' },
// { name: 'AppDomainName', field: 'AppDomainName' },
// { name: 'ProcessName', field: 'ProcessName' },
// { name: 'StackTrace', field: 'StackTrace' }
],
};
//$scope.vertexData = [
// {
// "First Name": "John",
// "Last Name": "Smith",
// },
// {
// "First Name": "Jane",
// "Last Name": "Doe",
// }
//];
$scope.load = function () {
ExceptionLogDataFactory()
.then(function (response) {
$scope.vertexData = JSON.parse(response.data);
});
}
$scope.load();
}
ExceptionLogDataController.$inject = ['$scope', 'ExceptionLogDataFactory'];
ExceptionLogDataFactory-
var ExceptionLogDataFactory = function ($http, $q, SessionService) {
return function () {
var result = $q.defer();
$http({
method: 'GET',
url: SessionService.apiUrl + '/api/ExceptionLogData',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + SessionService.getToken() }
})
.success(function (response) {
result.resolve(response);
})
.error(function (response) {
result.reject(response);
});
return result.promise;
}
}
ExceptionLogDataFactory.$inject = ['$http', '$q', 'SessionService'];
I've verified that my REST call is returning JSON data through Postman so the problem lies with my front end code.
Making progress...
I'm getting my json object successfully returned and am trying to display it with the following...
$scope.data = [];
$scope.gridOptions = {
enableSorting: true,
data: 'data',
};
ExceptionLogDataService() //Call to Service that returns json object
.then(function (data) {
$scope.data = data;
$scope.gridOptions.data = $scope.data;
console.log($scope.data);
}
And this is the json object that is being returned via console.log call...
Object { DataId: 1074, SourceDateTime: "2016-01-19T13:29:01.2512456-05:00", MessageText: "There is an error in XML document (…", IsDirty: false, StatusList: Object, FileName: "D:\ProdMonitorSiteDev\ErrorFiles\…", GenJIRATicket: false, MessageCount: 1, MachineName: "VERTEXCUTIL01", AppDomainName: "", 2 more… }
This is the error that I am getting...
Error: newRawData.forEach is not a function
Well I figured it out!
I finally got my head out of the weeds and 'really' looked at the JSON object that was being returned from my service and noticed that the object was encapsulated with '{}' (curly braces) which is what was causing the newRawData.forEach error. So what I did was the following...
.then(function (data) {
$scope.data = "[" + JSON.stringify(data) + "]"; // 'Stringify my object and then encapsulate it with square brackets '[]' and then I could use JSON.parse to then parse the new string into a JSON object...
$scope.data = JSON.parse($scope.data);
// Worked like a champ!....
$scope.gridOptions.data = JSON.stringify($scope.data);
You don't need to parse the JSON.
$http.get(url)
.success(function (data) {
$scope.gridOptions.data = data;
}
This should work just fine for what you are doing.

Publish from 2 collections in Meteor (list each user that liked post)

How can I query a collection for all users that "liked" this post and then put it in a template?
Collections:
likes: {
"_id": 1234,
"userId": "1dsaf8sd2",
"postId": "123445"
}, {
"_id": 1235,
"userId": "23f4g4e4",
"postId": "123445"
}
users: {
"_id": 1 dsaf8sd2,
"profile": {
"name": "Bob",
"details": "Cool sentence about Bob."
}
}, {
"_id": 23 f4g4e4,
"profile": {
"name": "Sam",
"details": "Cool sentence about Sam."
}
}
Publish:
Meteor.publish('likes', function(postSlug) {
check(postSlug, Object);
// find the post that matches slug and return its id
var postId = Posts.findOne({
slug: postSlug
}, {
_id: 1
});
// find all users that liked this post
var data = Likes.find({
postId: postId
}).forEach(function(doc) {
return Meteor.users.find({
_id: doc.userId
});
});
if (data) {
return data;
}
return this.ready();
});
Helper for template:
Template.listLikers.helpers({
likers: function(){
return this;
}
});
Now print out each result in template to list each liker of this post:
{{#each likers}}
<h1>{{name}}</h1>
<p>{{details}}</p>
See Full Profile
{{/each}}
I feel I either have my collections structured wrong or my forEach() is problematic.
Your problem can be solved by using Mongo's $in: selector as follows:
Meteor.publish('likes', function (postSlug) {
check(postSlug, Object);
var postId = Posts.findOne({ slug: postSlug},{ _id: 1 }); // find post that matches slug
var relatedLikes = Likes.find({ postId: postId },
{ fields: { userId: 1 }}).fetch(); // fetch the userId field from likes. _id will come with it
var userIdArray = _.pluck(relatedLikes,'userId'); // extract just the userIds into an array
return Meteor.users.find({ _id: { $in: userIdArray }});
});
Have you looked at reywood:publish-composite? It's excellent for collection joining problems such as this one.
As Michel Floyd suggests, you could use the reywood:publish-composite package:
Meteor.publishComposite('likes', function (postSlug) {
return {
find: function () {
return Posts.find({slug: postSlug});
},
children: [
{
find: function (post) {
return Likes.find({postId: post._id});
},
children: [
{
find: function (like) {
return Meteor.users.find({_id: like.userId});
}
}
]
}
]
}
});

AngularJS evaluate a string in a function to call property on json list

I wish I could give this a more descriptive title, but I don't really know the name of what I am trying to do. I have a JSON list in angular that looks like this:
$scope.users =
{
// list name and the "title" must be the same
Guest:
{
title: 'Guest',
list:
[
{ id: "0", name: "Stephen" },
{ id: "1", name: "Mitch"},
{ id: "2", name: "Nate"},
{ id: "3", name: "Rob" },
{ id: "4", name: "Capt. Jack"},
{ id: "5", name: "Herman" }
]
},
Admin:
{
title: 'Admin',
list:
[]
}
};
And I need to dynamically evaluate a string (either "Guest" or "Admin" or any other user-group that hasn't been created) in order to move a user from one user-group to another.
The function I am working with looks like:
$scope.moveUser = function(fromId, toId, index) {
scope.users.toId.list.push(scope.users.fromId.list[index]);
scope.users.fromId.list.splice(index, 1);
};
with "fromId" and "toId" being strings that evaluate to the name of a user-group ("Admin" or "Guest"). Right now, the function is trying to find a JSON field called "toId" and errors when it can't find any. How would I evaluate the string first so that if the toId == "Guest" and the fromId == "Admin", my function becomes:
scope.users.Guest.list.push(scope.users.Admin.list[index]);
scope.users.Admin.list.splice(index, 1);
change your $scope.moveUser function to
$scope.moveUser = function(fromId, toId, index) {
$scope.users[toId].list.push($scope.users[fromId].list[index]);
$scope.users[fromId].list.splice(index, 1);}
it is really work
If I understand correctly:
$scope.moveUser = function(fromId, toId, index) {
if (users.hasOwnProperty(fromId) && users.hasOwnProperty(toId)) {
scope.users.toId.list.push(scope.users.fromId.list[index]);
scope.users.fromId.list.splice(index, 1);
return true;
} else {
return false;
}
};

Categories