In my Nodejs site, I created a JSON array and sent it to the angularJs client. Then it shows as [object, object]. Because of that reason, I used JSON.stringify now it shows in a weird way in angularJs client.
Array creation in NodeJs side,
getAttachments = function () {
let attach = [];
workflowSession.files.forEach(file => {
if (file) {
const item = {
text: file.name,
link: workflowSession.metadata.portalBaseUrl + "api/files/" + workflowSession.workflowRef + "#"+ file.name
}
attach.push(item);
}
});
return attach;
};
When I put the console log in the Nodejs side it displayed as below,
[ { text: 'sdee.png',
link: 'http://localhost:3000/api/files/kYnDsXjyFT#sdee.png' },
{ text: 'wes.png',
link: 'http://localhost:3000/api/files/kYnDsXjyFT#wes.png' }
]
But in AngularJs client shows it as [object, object], because of that reason I made the changes to the above array creation method as below,
getAttachments = function () {
let attach = [];
workflowSession.files.forEach(file => {
if (file) {
const item = {
text: file.name,
link: workflowSession.metadata.portalBaseUrl + "api/files/" + workflowSession.workflowRef + "#"+ file.name
}
attach.push(item);
}
});
return JSON.stringify(attach);
};
Then NodeJs side shows data for console.log as below,
[
{"text":"sdee.png","link":"http://localhost:3000/api/files/kYnDsXjyFT#sdee.png"}, {"text":"wes.png","link":"http://localhost:3000/api/files/kYnDsXjyFT#wes.png"}
]
But in AngularJs side shows it in the as below,
[
{"text":"wes.png","link":"http://localhost:3000/api/files/saJiCDZPet#wes.png"},{"text":"ssdd.png","link":"http://localhost:3000/api/files/saJiCDZPet#ssdd.png"}
]
I want to iterate this array as shown in below HTML snippet, but I can't do that because of this format issues. The "action.links" is the array created from the Nodejs side.
<md-menu-content>
<md-menu-item ng-repeat="item in action.links" ng-if="item.link">
<md-button href="{{item.link}}" target="_blank">
{{item.text}}
</md-button>
</md-menu-item>
</md-menu-content>
What am I doing wrong?
Looks like the Angular side is getting HTML encoded, what you could do is run it through an HTML decode:
var htmlDecode = function(str) {
var temp = document.createElement('span');
temp.innerHTML = str;
return temp.textContent;
};
var foo = '[{"text":"wes.png","link":"http://localhost:3000/api/files/saJiCDZPet#wes.png"},{"text":"ssdd.png","link":"http://localhost:3000/api/files/saJiCDZPet#ssdd.png"}]';
console.log(
htmlDecode(foo)
);
Ideally though you would keep it from getting HTML encoded in the first place. If you're able to share a live version of your code it would be easier to debug why this is happening.
You don't need to stringify the JS object on the node.js side. Based on what you've provided, the [object, object] syntax you're seeing when logging in the console may be okay. Did iteration over the array not work when it was being returned as an array of objects?
If you want to see the data using console.log on the client side, stringify the object there:
console.log(JSON.stringify(action.links));
You will not be able to iterate over a JSON array because it's a string and would need to be parsed back to an array of objects first.
Related
[
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]
Above is my JSON Array that is stringified,I tried to JSON.parse and other functions like iterating it in a for loop but the key values also got scrambled.
Is there any way or an npm method that could instantly output the retrieved variable?
var cartItemFromLocalStorage = JSON.parse(localStorage.getItem("cartitem"));
if (cartItemFromLocalStorage != null) {
console.log("It came defined");
console.log("This is OG Array: " + cartItemFromLocalStorage);
let cartItemObject = {
//set object data
comicid: this.state.comicId,
purchasetype: this.state.purchaseType,
};
console.log(cartItemObject);
cartItemFromLocalStorage.push(cartItemObject);
localStorage.setItem("cartitem", result); //localstorage only supports strings
toast.success("Item Added to cart");
}
I checked the consoles and the states are putting up the data correctly.
I'm an extreme beginner in react js, help is much appreciated
The "JSON" you have written is actually JavaScript, not JSON. To convert it JSON use the JSON.stringify function, like so
> JSON.stringify([
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]);
'[{"comicid":"5f55e91271b808206c132d7c","purchasetype":"pb_single"}]'
and then replace the value in localStorage with it.
Even easier would be to type into the developer console
localStorage.setItem("cartitem", JSON.stringify([
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]));
So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply
Hi guys Im trying to print a list of scores saved within a database, ive got the data as JSON data (see below)
I am trying to print all each object within the "Scores" array using the following code
function showScores() {
var ourRequest = new XMLHttpRequest();
var x, i = "";
ourRequest.open('GET', '/allScores');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
for (i in ourData.scores) {
x += ourData.scores[i] + "<br>";
}
document.getElementById("scoresList").innerHTML = x;
};
ourRequest.send();
}
However it is printing out the following
Any help with this is greatly appreciated, thanks guys
This line tries to append a raw object to your HTML string:
x += ourData.scores[i]
Javascript can’t magically parse this into HTML for you, so it just outputs [object Object].
You need to build a string from the individual parts of this object and print that instead. For example:
Note that you should not use for ... in with an array
ourData.scores.forEach(function (score) {
x += `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
});
Which would output something like this for each score:
[H] Arsenal 2 - 2 Newcastle [A]
Be sure to set x = "" before the loop otherwise the string will still start with undefined.
In case you’re interested: there are more succinct ways of writing this loop. Using Array.map() for instance:
let x = ourData.scores.map(score => {
return `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
}).join();
This expression does not require initialization of x beforehand.
you can create the elements as string and you can join the entire array and assign it to the innerHTML, as shown below.
You can change the structure, here for example i had made to ul , li you can create table or whatever format.
Note if you want to just append it, since the object you can't directly append it using JSON.stringify which will convert your object into string.
I hope this will solve your issue. Please let me know if any other issue you are facing.
var jsonObj = {scores: [{"Away_Score": 2, "Away_Team": "Newcastle", "Home_Score": 2, "Home_Team": "Arsenal"}, {"Away_Score": 2, "Away_Team": "Napoli", "Home_Score": 4, "Home_Team": "Liverpool"}]}
var html = jsonObj.scores.map(o => {
return `<ul><li>${o.Away_Team}</li><li>${o.Away_Score}</li><li>${o.Home_Team}</li><li>${o.Home_Score}</li></ul>`
})
document.getElementById("todaysData").innerHTML = html.join("")
<div id="todaysData">
</div>
As title, when I try to do:
myString = JSON.stringify($('#calendar').fullcalendar('clientEvents'));
it fails. I tried to alert myString but I see a series of [Object object], ... . But if i try to alert myArray[0].title for example, it returns correctly.
Where I'm doing wrong?
P.S. The goal is to obtain a string to save on a file via AJAX.
Your results tell you that the objects in the array that the fullCalendar clientEvents method gives you can't be directly converted to JSON. I get slightly different results on the http://fullcalendar.io page (I get an error about trying to convert a circular structure); I assume that's down to differences either in the FullCalendar version you're using vs. they're using, or differences in how your browser and mine deal with circular structures. Either way, the objects apparently can't be used as-is.
The goal is to obtain a string to save on a file via AJAX.
You can do that by using map on the array to get objects that can be converted to JSON successfully, whitelisting the properties you want (or blacklisting the ones you don't want).
Here's an example whitelisting the start, end, and title properties:
var json = JSON.stringify($("#calendar").fullCalendar("clientEvents").map(function(e) {
return {
start: e.start,
end: e.end,
title: e.title
};
}));
Heres one blacklisting source and any property starting with _:
var json = JSON.stringify($("#calendar").fullCalendar("clientEvents").map(function(e) {
var rv = {};
Object.keys(e)
.filter(function(k) {
return k != "source" && !k.startsWith("_");
})
.forEach(function(k) {
rv[k] = e[k];
});
return rv;
}));
...which worked for me on their site.
Here are ES2015 versions of both of those:
Whitelisting:
let json = JSON.stringify($("#calendar").fullCalendar("clientEvents").map(e => ({
start: e.start,
end: e.end,
title: e.title
})));
Blacklisting:
let json = JSON.stringify($("#calendar").fullCalendar("clientEvents").map(e => {
let rv = {};
Object.keys(e)
.filter(k => k != "source" && !k.startsWith("_"))
.forEach(k => {
rv[k] = e[k];
});
return rv;
}));
i try to build json structure object dynamically according examples i saw in the net but with no success.
this is the json i try to build:
{
"campaigns": [
{
"campaign_id":,
"profile_id":,
"state":,
"goal":
},
{
"campaign_id":,
"profile_id":,
"state":,
"goal":
}
]
}
and this is the code :
this function called each time there is data to build the campaigns (in the json) element
var campaignsJson ={};
campaignsJson.campaigns =[];
var i = 0;
function buildJson(stateCampaignId,
profile_id,
stateSelectedValue,
dailyImpressionGoalValue,
pacingValue,
segmentGroupTargetsUpdatedataValue,
frequencytypeProfileValue,
frequencysetProfileValue
)
{
campaignsJson.campaigns[i].campaign_id = stateCampaignId;
campaignsJson.campaigns[i].profile_id = profile_id;
campaignsJson.campaigns[i].state = stateSelectedValue;
campaignsJson.campaigns[i].goal = dailyImpressionGoalValue;
i++;
var campaignsJsonstringify = JSON.stringify(campaignsJson);
alert(campaignsJsonstringify);
}
it gives me "cannot set property campaign_id of undefined"
what does it means ?and why ?
Just before
campaignsJson.campaigns[i].campaign_id = stateCampaignId;
add this :
campaignsJson.campaigns[i] = {};
So that there is an object onto which you'll be able to set properties.
Now, please, don't speak of "JSON structure". What you build is a plain standard JavaScript object while JSON is only the string based exchange format.