I have this in my console chrome:
[{"id":40,"endDate":"2017-04-22","dataA":"2017-04-19","nrC":2,"type":"CO","dataD":"2017-04-19","startDate":"2017-04-20"},{"id":40,"endDate":"2017-04-26","dataA":"2017-04-26","nrC":4,"tyoe":"CP","dataD":"2017-04-23","startDate":"2017-04-25"},
This json string is comming from the servlet that calls DAO class to take the information from db.
So, this string is (dynamically) passed into a jsp page from request session...and i put it into var DAYS = '${jsonArrayString}'; then console.log(DAYS); then it prints that json string above.
So...it can print more data then two.
It has to be put into a javascript variable loke this:
var DAYS = '${jsonArrayString}'; //That's what's on my console..and it comes from session into this jsp page
I think it has to be iterated through a foreach and print it in that format.
var USER_DAYS = [
{
id: value from jsonArrayString,
date: value from jsonArrayString,
title: value from jsonArrayString,
start: new Date(value from jsonArrayString),
end: new Date(value from jsonArrayString),
allDay: true,
className: 'done'
},
];
I tried to put the values manually and it works...like this:
var USER_DAYS = [
{
id: 1,
date: '2017-04-05',
title: 'CO',
start: new Date(2017, 3, 5),
end: new Date(2017, 3, 7),
allDay: true,
className: 'done'
},
I don't know hot to put the values from that json string(
Which can be anythong ... more than 2 records)...that why I need to iterate through that json string.
I want the values to be put only in that format, in that variable (var USER_DAYS)
I tried somthing like this, but it does't work:
<c:forEach items="${jsonArrayString}" var="jsonArrayString">
{
id: '${jsonArrayString.nrC}' ,
date: '${jsonArrayString.dataD}' ,
title: '${jsonArrayString.type}' ,
startDate: '${jsonArrayString.startDate}',
endDate: '${jsonArrayString.endDate}',
allDay: true,
className: 'done'
},
</c:forEach>
];
or like this:
var USER_DAYS = [
{
id: DAYS.nrC,
date: DAYS.dataD,
title: DAYS.type,
start: new Date(DAYS.startDate),
end: new Date(DAYS.endDate),
allDay: true,
className: 'done'
},
];
How to do this?
try parse to json string into json objects.
Example
var USER_DAYS = JSON.parse('${jsonArrayString}')
JavaScript code runs only on the client side, while JSP on the server. You cannot iterate over the JavaScript variable while the page is rendered at the server.
If you want to serve a page that already contains the data, you should pass the data to the JSP page as a model attribute. To do this, take a look at this post.
If you want to populate the page with data after it has been loaded to the browser, you have to use a JavaScript library, such as jQuery. In this case, you have to send a request to the server to get the data in JSON format, and then you can manipulate them on the client side.
Related
I am working on some trains' open data feed and getting some JSON as a response from a server. I parse this JSON into a data variable and display it as seen below. However, I cannot find a way to iterate over the response to be able to manipulate each message. I want to iterate over each message and then use the data for a record in a SQL database. I cannot get to the point of accessing any individual message data.
How can I create a loop to iterate over each message and extract it's data?
[
{
SF_MSG: {
time: '1666370311000',
area_id: 'TD',
address: '0C',
msg_type: 'SF',
data: '1F'
}
},
{
CA_MSG: {
to: '4333',
time: '1666370311000',
area_id: 'WO',
msg_type: 'CA',
from: '4331',
descr: '2K60'
}
}, ...
]
Edit: using data.forEach(function(message) produces an output of the structure:
{ CA_MSG: { to: '6021', time: '1666372120000', area_id: 'CY', msg_type: 'CA', from: 'STIN', descr: '2Y73' } }
, however, how do I query this inner object, the names of the objects will differ depending on message type if this matters?
try this:
data = JSON.parse(yourJSONdata)
data.map((o, i)=>{
//o is the object, i is the index
// do your processing here
then at the end do
data[i]=processedobject
})
Im completely lost. This is some test code I use to print a specific key of an object, then im printing the entire object.
console.log(docs[0].mc_ign);
console.log(docs[0]);
Now this is the output I see on the console:
The__TxT
{
id: 0,
status: 1,
testing: false,
_id: 5dbc17eb20b3a8594d569570,
timestamp: 2019-11-01T11:32:59.380Z,
mc_uuid: 'dac89e44d1024f3b810478ed62d209a1',
discord_id: '653029505457586176',
email_address: 'gut97930#eveav.com',
country: 'Germany',
birth_month: 3,
birth_year: 1943,
about_me: 'about me text',
motivation: 'motivation text',
build_images: '',
publish_about_me: true,
publish_age: false,
publish_country: true,
__v: 0
}
Where is the mc_ign key?
The object itself comes from mongoose, the missing key is added by me after the fact:
docs[i].mc_ign = mc_ign;
I tried logging the entire object before and after I add the key and assign the value. They are both the same.
What am I missing? Why can I read the value out, but cant see it?
It is mongoose document object. To achieve what you want do the following.
docs[0] = docs[0].toObject();
docs[0].mc_ign = "stuff";
console.log(docs[0])
.toObject() convert it to plain JS object.
This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 4 years ago.
I very new to programming and I can't find the solution of my issue, can you give me the solution please?
I have this JSON file:
{
"groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]"
}
And I need something like this in my js (but i want import my JSON to get array like this) :
const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]
I don't know how to do without using jQuery.
I already tried with this:
const json = require('./test.json');
This code returns an object:
It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above.
How can achieve this?
The value of groups is not valid JSON: string values should be surrounded by double-quote marks, and so should keys. The file with valid JSON in that string would look like this:
{
"groups": "[{ \"id\": 1, \"title\": \"group 1\" }, { \"id\": 2, \"title\": \"group 2\" }]"
}
Of course if you have control over the creation of this file, it would be better to have this value as part of the native JSON content, rather than JSON-in-a-string-inside-JSON. If that's not possible, you will need to correct the quoting in the string yourself, which can be done with a couple of Regular Expression replacements.
/* obj is the object in the JSON file */
var json_str = obj.groups.replace(/'/g,"\"").replace(/([a-z]+)\:/g,"\"$1\":");
var groups = JSON.parse(json_str);
Alternatively, although the string is not valid JSON it is a valid Javascript expression, so if the contents of the file are trustworthy, you can also do it with eval:
var groups = eval(obj.groups);
I just need to fill my array "groups" like that :
[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]
with a json file and without jquery
Since I didn't notice the "without jQuery" in the original question, here is a new answer:
var request = new XMLHttpRequest();
request.open('GET', './test.json', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
It does two things:
1. Loads the json file
2. Parses the loaded string into a javascript object.
Before you can even do anything with your JSON file, you need to load it. jQuery has a shortcut, which will even automatically parse the JSON-string into a native JS object for you:
$.getJSON('./test.json', function(data) {
console.dir(data);
});
https://api.jquery.com/jquery.getjson/
if you can't edit original text, you need replace ' to " and then did JSON.parse(json.groups);
otherwise you can change a little your json like this:
JSON.parse('[{ "id": 1, "title": "group 1" }, { "id": 2, "title": "group 2" }]')
be careful with " and ' parentheses
{
"key":"string"
}
string with defined with ' parentheses not valid
in JSON keys must be to in "" parentheses
You can parse the object to an array this way:
Object.values(YOUR_OBJECT)
docs: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/values
I'm trying to format a JSON date to a JavaScript date to display it in a nice way. The original date comes from a JSON-object, which looks like this:
{
"name": "foo",
"num": "1",
"date": "\/Date(1367539200000)\/"
}
The place where the JSON elements should be displayed later is a SAPUI5 object header:
objectHeader = new sap.m.ObjectHeader({
title: "{/name}",
number: "{/num}",
attributes: [
new sap.m.ObjectAttribute({
text: "{/date}"
})
]
});
Since the JSON object is bound to the object header via
dataModel.setData(json)
objectHeader.setModel(dataModel)
the values are correctly substituted. But i want to have the date correctly formatted to a more readable format instead of seeing /Date(1367539200000)/ on my website. I tried with
new sap.m.ObjectAttribute({
text: new Date(parseInt("{/date}".substr(6))).toLocaleString('de');
})
But that failed with an 'Invalid Date'. What would be the right syntax to format the JSON date to a Javascript data object in a model binding?
You can use a formatter to do that for you. The advantage is that you can properly use databinding, so your controls will be updated automatically in case the model changes.
new sap.m.ObjectAttribute({
text: {
parts: [
{path: "/date"}
],
formatter: function(date){
//do whatever you want
return /* the value you want to have as result */;
}
}
})
Im using the local notifications plug-in https://github.com/katzer/cordova-plugin-local-notifications, and i'm trying to schedule multiple notifications but I only get the first one.
It has something to do with the id, but I don't know if it suppose to be a object or a value I've been tracing this everywhere and are really grateful for all help!
var now = new Date().getTime(),
_60_seconds_from_now = new Date(now + 30*1000);
_120_seconds_from_now = new Date(_60_seconds_from_now.getTime() + 60*1000),
window.plugin.notification.local.add({
id: 28,
title: 'Reminder',
message: 'Dont forget to buy some ds.',
repeat: 'minutely',
date: _60_seconds_from_now
});
window.plugin.notification.local.add({
id: 27,
title: 'Reminder',
message: 'Dont forget to buy some dsfsdafsdafsdaf.',
repeat: 'minutely',
date: _120_seconds_from_now
});
I think by making repeat minutely first one is overlapping the second one... make sense ??