I have a JSON object like this:
var post = {
"post_id": "1",
"content": "content",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
"likes_count": 0,
"likers": [],
"comments_count": 0,
"commenters": [],
"comments": []
};
And post is passed to the function given below from the front end.
var vm = this;
vm.likePost = function(post) {
var likedPost = post;
vm.userInfo();
likedPost.likers.push(userObject); //Here
myService.postLike(likedPost).success(function(data) {
likedPost.isLiked = true;
likedPost.likes_count++;
vm.posts = data;
});
};
But doing so, I get a JavaScript error saying push is not a function in line likedPost.likers.push(userObject);
And userObject is returned by vm.userInfo() and it looks like this:
vm.userInfo = function() {
myService.getBasicUserInfo().success(function(data) {
vm.currentPost.post_author.id = data.id;
vm.currentPost.post_author.firstName = data.firstName;
vm.currentPost.post_author.lastName = data.lastName;
});
};
and the returned JSON is like this:
{"id":"12","firstName":"Amelia","lastName":"Earheart"}
Can anyone help me figure out the cause of this issue?
UPDATE:
{
"post_id": "12",
"content": "Content is the content that contains the content",
"image": "member-default.jpg",
"created_at": "2016-05-26 14:29:00",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
}
This is what I get upon console.log(likedPost);
The output clearly specifies that likers is not defined. You can put a validation check before using push() method.
//if likedPost.likers is not defined, it will define it as an array
likedPost.likers = likedPost.likers || [];
//Do the push operation
likedPost.likers.push(userObject);
Your likedPost object doesn't have the likers array you expect. Probably you can see if that exists before trying to push.
if (typeof likedPost !== 'undefined')
likedPost.likers.push(userObject);
Related
I am returning a json as shown below,
{
"entities": {
"permissions": {
"77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
"id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"role": "ADMIN",
"permissions": null,
"canAccessAllAccounts": true,
"allowedAccounts": null,
"createdAt": "2022-01-30T18:20:46.901Z",
"updatedAt": "2022-01-30T18:20:46.901Z",
"deletedAt": null
}
},
"users": {
"9bba4c96-781b-4012-9a48-071c1cb5ec24": {
"id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
"username": "246e6555eb16e3c8#ator.com",
"activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
"enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
"permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"firstName": "a48d1eb7270bb404",
"lastName": "e0aaa6d09e19",
"avatarUrl": null,
"sendBookingRequestEmail": true,
"isSSO": false,
"createdAt": "2022-01-30T18:20:46.999Z",
"updatedAt": "2022-01-30T18:20:46.999Z",
"deletedAt": null,
"permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
}
}
},
"result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}
I am trying to get permissionsid value (it is occurred three places in the JSON), also forgot to mention in the original comment that these alphnumeric values in permissionid and userid are dynamics
When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser['permissionId'];
When I am using the following, I am getting Cannot read properties of undefined (reading 'id')
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0].id;
When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0];
When I am using the following, I am getting [object%20Object]
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions;
What I am missing here, couldn't find same kind of question
Why stringify and parse?
Anyway, it is more complex than you think
const obj = JSON.parse(str)
console.log(Object.values(obj.entities.users)[0].permissionId)
<script>
const str = `{
"entities": {
"permissions": {
"77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
"id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"role": "ADMIN",
"permissions": null,
"canAccessAllAccounts": true,
"allowedAccounts": null,
"createdAt": "2022-01-30T18:20:46.901Z",
"updatedAt": "2022-01-30T18:20:46.901Z",
"deletedAt": null
}
},
"users": {
"9bba4c96-781b-4012-9a48-071c1cb5ec24": {
"id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
"username": "246e6555eb16e3c8#ator.com",
"activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
"enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
"permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"firstName": "a48d1eb7270bb404",
"lastName": "e0aaa6d09e19",
"avatarUrl": null,
"sendBookingRequestEmail": true,
"isSSO": false,
"createdAt": "2022-01-30T18:20:46.999Z",
"updatedAt": "2022-01-30T18:20:46.999Z",
"deletedAt": null,
"permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
}
}
},
"result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}`</script>
I see only 2 places, but in any cases remove this from your code
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
since your response data is parced already automatically
Since you can have several permissions or users , you can not get your data just using [0] or [1] since you don' t know how many users can be in the response. So try this code ( it was tested and working properly)
var permissionIds=[];
Object.values(response.entities.permissions).forEach(element => {
permissionIds.push(element.id)
});
var userIds=[];
Object.values(response.entities.users).forEach(element => {
userIds.push(element.id)
});
Here is my fiddle: DEMO
I want my JSON to be as below on click of "Save Actions" and when the category is "SMS". I'm not able to achieve this.
Also, the form fields change on change of category.
{
"name": "",
"category": "SMS",
"description": "",
"apiUrl": "",
"apiMethod": "GET",
"apiPayload": {
"senderName": "",
"number": "",
"message": ""
},
"#class": "action"
}
Any help would be much appreciated. Thanks :)
Move the apiPayload out of the reduce callback function.
And assign the value after the reduce loop.
$('#saveActions').on('click', function(e) {
var apiPayload = {};
var jsonData = $('form.form-horizontal#events')
.find(':input:not(button):not(#new-option-event)').get()
.reduce(function(acc, ele) {
if (ele.closest('.payload')) {
var i = 0;
apiPayload[ele.name] = ele.value.trim();
} else {
acc[ele.name] = ele.value.trim();
}
return acc;
}, {});
jsonData['apiPayload'] = apiPayload;//assign value
jsonData['#class'] = "action";
alert(JSON.stringify(jsonData, null, 4));
});
I'm having trouble getting two JSON APIs on a website to merge into a single array rather than two.
My two JSON strings look like this:
{
"users": [
{
"name": "test1",
"uniqueid": "randomlygeneratedUUID"
},
{
"name": "test2",
"uniqueid": "randomlygeneratedUUID"
},
{
"name": "test3",
"uniqueid": "randomlygeneratedUUID"
}
}
{
"users": [
{
"name": "test4",
"uniqueid": "randomlygeneratedUUID"
},
{
"name": "test5",
"uniqueid": "randomlygeneratedUUID"
},
{
"name": "test6",
"uniqueid": "randomlygeneratedUUID"
}
}
and using something like Request, I grab the two URLs (the code looks like this):
var RequestMultiple = function (urls, callback) {
'use strict';
var results = {}, t = urls.length, c = 0,
handler = function (error, response, body) {
var url = response.request.uri.href;
results[url] = { error: error, response: response, body: body };
if (++c === urls.length) { callback(results); }
};
while (t--) { request(urls[t], handler); }
};
var DoRequest = function() {
var urls = ["url1", "url2"];
RequestMultiple(urls, function(responses) {
for (url in responses) {
response = responses[url];
if (response.body){
var JsonBody1 = JSON.parse(response[urls[0]]);
var JsonBody2 = JSON.parse(response[urls[1]]);
var MergeJsonBody = JsonBody1.concat(JsonBody2);
console.log(JSON.stringify(MergeJsonBody).toString());
} else {
console.log('Url', url, response.error);
}
}
});
});
console.log(DoRequest());
The issue I'm having is it doesn't merge, but when it does it looks like this:
{"users": [{ "name": "test1","uniqueid": "randomlygeneratedUUID"},{ "name": "test2","uniqueid": "randomlygeneratedUUID"},{ "name": "test3","uniqueid": "randomlygeneratedUUID"}} unidentified {"users": [{ "name": "test4","uniqueid": "randomlygeneratedUUID"},{ "name": "test5","uniqueid": "randomlygeneratedUUID"},{ "name": "test6","uniqueid": "randomlygeneratedUUID"}}
And it returns an error about the string unidentified.
When I don't get that error, it only shows the second JSON body.
What am I doing wrong? And is there a module or a best in practice way to do this?
EDIT:
Okay I took the solution provided, and I still hit a wall. To counter the issues I basically just had two unique requests that add to a local array variable, then once the command was triggered, create the array, then erase all the items from the array and start all over again. Thanks for all the help!
First of all both of your JSONs are missing closing square brackets. I guess its typo but below is the correct JSON.
{
"users": [
{
"name": "test4",
"uniqueid": "randomlygeneratedUUID"
},
{
"name": "test5",
"uniqueid": "randomlygeneratedUUID"
},
{
"name": "test6",
"uniqueid": "randomlygeneratedUUID"
}
]
}
Now change below line of code
JsonBody1.concat(JsonBody2);
to
JsonBody1.users.concat(JsonBody2.users);
This will should give you expected results. You are doing concat on the actual objects instead of arrays.
I am getting a json response that looks like this :
{
"+143500000": {
"inbox": "active",
"Messages": [{
"id": "sms001",
"Sender": "Tom",
"Text": "hello world"
}, {
"id": "sms002",
"Sender": "Jones",
"Text": "bye world"
}]
}
}
I want to save this response to local storage but it needs to look like this
{
"+143500000": {
"inbox": "active",
"Messages": {
"sms001": {
"Sender": "Tom",
"Text": "hello world"
},
"sms002": {
"Sender": "Jones",
"Text": "bye world"
}}
}
}
How can i modify the response i get to make it look like that. I am a beginner at javascript. Your help would be greatly appreciated. Would love a sample in javascript or jquery to do this .
Thanks
The logic should be very easy to follow. Note that your starting json has Messages as an array, but you are requesting that it have named properties, so it must be turned into an object.
var data = {
"+143500000": {
"inbox": "active",
"Messages": [
{
"id":"sms001",
"Sender":"Tom",
"Text": "hello world"
},
{
"id":"sms002",
"Sender":"Jones",
"Text": "bye world"
}
]
}
};
var messages = {};
for (var i=0; i<data["+143500000"].Messages.length; ++i) {
var item = data["+143500000"].Messages[i];
messages[item.id] = item;
delete messages[item.id].id;
}
data["+143500000"].Messages = messages;
console.log(data);
data = JSON.stringify(data);
console.log(data);
localStorage.myJson = data;
console.log(localStorage.myJson);
var retrievedData = localStorage.myJson;
console.log(retrievedData);
Live demo here (click).
// if your value is in `a`, then:
for (k in a)
if (a.hasOwnProperty(k)) {
hash = {};
a[k].Messages.forEach(function(m) {
hash[m.id] = m;
delete m.id;
});
a[k].Messages = hash;
}
I'm using javascript with a json library and running into a little trouble. Here's my json output:
{
"artist": {
"username": "myname",
"password": "password",
"portfolioName": "My Portfolio",
"birthday": "2010-07-12 17:24:36.104 EDT",
"firstName": "John",
"lastName": "Smith",
"receiveJunkMail": true,
"portfolios": [{
"entry": [{
"string": "Photos",
"utils.Portfolio": {
"name": "Photos",
"pics": [""]
}
},
{
"string": "Paintings",
"utils.Portfolio": {
"name": "Paintings",
"pics": [""]
}
}]
}]
}
}
In javascript I'm trying to access the entries in the map like so:
var portfolios = jsonObject.artist.portfolios.entry;
var portfolioCount = portfolios.length;
for ( var index = 0; index < portfolioCount; index++ )
{
var portfolio = portfolios[index];
txt=document.createTextNode("Portfolio Name: " + portfolio['string'] );
div = document.createElement("p");
div.appendChild ( txt );
console.appendChild(div);
}
but portfolios is "undefined". What's the correct way to do this?
Look at your JSON results. portfolios is a one-element array; portfolios[0] is an object containing a single key, entry, which maps to an array of two objects that have both string and utils.Portfolio keys. Thus, the syntax jsonObject.artist.portfolios.entry will not work. Instead, you want jsonObject.artist.portfolios[0].entry.
If possible, I would suggest changing whatever code generates those JSON results to remove the entry level of indirection entirely, e.g. like so:
{
"artist": {
/* ... */
"portfolios": [
{
"string": "Photos",
"utils.Portfolio": {
"name": "Photos",
"pics": [""]
}
},
{
"string": "Paintings",
"utils.Portfolio": {
"name": "Paintings",
"pics": [""]
}
}
]
}
}
Then you could access it with
var portfolios = jsonObject.artist.portfolios;
for (var i = 0, portfolio; portfolio = portfolios[i]; ++i)
{
// use portfolio variable here.
}
There is an array in your object. I believe you're looking for this:
var portfolios = jsonObject.artist.portfolios[0].entry;
The portfolios property is an array, so you need to use an index to get the first element:
var portfolios = jsonObject.artist.portfolios[0].entry;