I am getting JSON value from my server and it works well. But I want to customize my JSON value. I have two questions:
First, when I get region value, I get it like ["USA"],["Mexico"],["Canada"]. Is there a way I can ignore the double quotes/brackets and just get the strings values like USA, Mexico, Canada?
Second, when I get the regDate value I get the whole data like 2018-10-31T07:53:12.000Z instead, can I ignore some values and get it like 2018-10-31 07:53?
{
"result": "ok",
"data": [
{
"idx": 1,
"region": "[\"USA \", \"Mexico \", \"Canada \"]",
"regDate": "2018-10-31T07:53:12.000Z"
}
]
}
Seems that your region data was double-encoded. In javascript, you'll want to decode that, e.g.
const response = {
"result": "ok",
"data": [
{
"idx": 1,
"region": "[\"USA \", \"Mexico \", \"Canada \"]",
"regDate": "2018-10-31T07:53:12.000Z"
}
]
};
const regions = JSON.parse(response.data[0].region);
For time formatting, you could use the built-in Javascript Date type, such as..
const regDate = new Date(response.data[0].regDate);
const regDatestr =
regDate.getUTCFullYear() + '-' +
regDate.getUTCMonth() + '-' +
regDate.getDate() + ' ' +
regDate.getUTCHours() + ':' +
regDate.getUTCMinutes()
;
If you need more functionality than the built-in, I would recommend date-fns.
You'd save the results of your JSON query to a variable data. Then you'd do this:
var countries = "";
for (var i = 0; i < data[0].region.length; i++) {
countries += data[0].region[i];
}
var time = data[0].regDate.split("000Z");
Related
So more sprcifically, this POST request needs to do the below procedures:
1) To find if all the characters from 2 sets of characters are contained in a third set of characters.
2) The 3 sets of characters are given/inserted as parameters in the body request
3) Caps/ or no Caps does not matter in this case. Same goes for spaces.
4) Example of an input:
{"testees": [ "abc", "cde" ], "subject": "acbcde"}
5) Example of an output:
{
"success": true,
"error": null,
"stack": null,
"result": true
}
I'm working out this API with the use of "POSTMAN".
I found some articles like this one: https://attacomsian.com/blog/ways-to-check-string-contains-substring-javascript
But still, I wasn't able to make it work.
I've tried many different things both here and with the previous POST requests I had to make.
The problems this time are:
1) The type of my input. Should it be an object? Should it be a string? I don't know.
2) But most importantly: How to check if every single character from both the 1st and 2nd set of characters is contained in the 3rd set of characters?
app.post("/api/contained", function (req, res) {
var input = {
testees: toString,
subject: toString
}
input.testees = req.body.testees;
input.subject = req.body.subject;
var output = {
success: false,
error: null,
stack: null,
result: false
}
console.log("Type: " + typeof input.testees + ", Value: " + input.testees + ", Length: " + input.testees.length)
console.log("Type: " + typeof input.subject + ", Value: " + input.subject)
The types should be as you specified them in your example.
{"testees": [ "abc", "cde" ], "subject": "acbcde"}
testees as an Array with both of the sets that you are willing to check and subject as a String that you would like to perform the checks on.
The check mechanism should be relatively simple:
let flag = true;
function checkSet(charsSet) {
const chars = charsSet.split('');
for (let i = 0; i < chars.length; i++) {
const char = chars[i].toLowerCase();
if (!input.subject.toLowerCase().includes(char)) {
flag = false;
break;
}
}
}
const [set1, set2] = input.testees; // Destruct both sets.
checkSet(set1);
// You can check if "flag" is already false here and not run the second check for better performances.
checkSet(set2);
if (flag) {
// Both sets are contained inside the third set.
} else {
// One or more of the sets is not contained inside the third set.
}
If my AJAX call returns something like this:
{
"data": {
"name": "Configuration ID",
"type": "string",
"editor": "editableText"
}
}
And I have a variable defined as:
var editableText = $("<div/>").dynamicTableEditor({
editHandler: function(aData, aContext) {
$("#save-data").html("Saving note: <strong>" + aData + "</strong>");
}
});
Is it possible to have to have a variable so that the output would be:
"name": "Configuration ID",
"type": "string",
"editor": $("<div/>").dynamicTableEditor({
editHandler: function(aData, aContext) {
$("#save-data").html("Saving note: <
strong > " + aData + " < /strong>");
}
})
If you just want the string of
$("<div/>").dynamicTableEditor({
editHandler: function(aData, aContext) {
$("#save-data").html("Saving note: <
strong > " + aData + " < /strong>");
}
})
Then it is possible. You can make it as a string and deserializate it any time you want.
I dont know what the return type of dynamicTableEditor() is. If it is a value which can be converted to a String, like abcde which can be converted to "abced", then the answer is yes.
You need to understand what the JSON is. JSON just make everything as a string. So if there is a variable you cannot convert to a string, then the answer is no.
I"m attempting to build a string in order to put the results in a DataTables table.
I'm taking an array and using regex to get everything in it's own index and my resultant string array is this:
["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"]
One big string array with everything in its own index. Next I'm using a loop and building a string in order to pass it to a datatables table. The result of which SHOULD look like this:
var dataString = [
["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Instead I'm getting this:
var dataString = undefined["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Here is my loop code to build the string from the array:
for(var i = 0; i < routePoints.length-3; i+=3){
console.log(routePoints);
if(i >= 0 && i < routePoints.length - 4){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"],';
}else if(i == routePoints.length - 3){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"]';
}
}
If I simply deleted the "undefined" and paste the code in, the datatabe populates fine, but I cannot see where the undefined is even coming from. Thanks for the second set of eyes!
Usually, the undefined comes from your initialization. I don't see the code here, but you probably have something like:
var dataSetString;
instead, you should always start an empty string as:
var dataSetString = "";
As to why this happens. All uninitialized variables default to undefined. When you use the += operation, it will try to interpret what your are doing (if you have two numbers it will add them, two strings: concatenate). Undefined has no good += operation, so it uses the second part of the operation the string you are passing in. So, it automatically converts the undefined to a string and concatenates the new string to it, ending up with "undefined[blah,blah,blah"
You shouldn't compose a String like that.
It doesn't look like you need a string anyway but a 2D array.
var data = ["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"
];
var dataString = [];
for (var i = 0; i < data.length; i+=3) dataString.push(data.slice(i, i + 3));
console.log(dataString);
// Should you actually need a string, you can use JSON.stringify()
console.log(JSON.stringify(dataString));
I Have this kind of JSON Object
"{\"date\": \" 9 Marzo\", \"time\": \" 07:00 - 13:20\", \"descrizione\": \" concerto\", \"alimenti\": [{ \"macchina\":\"si\", \"pollo\":\"no\" }] }";
I want to get exactly the string "macchina" and "pollo", which are the keys text/value (I get the Object from an ajax, so "9 Marzo" would be like response.date), and same for "si" and "no", I cannot arrive to them.
I have tryed console.log(response.alimenti[i][0]); but it's undefined.
i come from the cicle: for (i = 0; i < response.ruoli.length; i++)
This will get you to the strings "macchina" and "pollo":
var json = "{\"date\": \" 9 Marzo\", \"time\": \" 07:00 - 13:20\", \"descrizione\": \" concerto\", \"alimenti\": [{ \"macchina\":\"si\", \"pollo\":\"no\" }] }";
var obj = JSON.parse(json);
for (var k in obj.alimenti[0]) {
console.log(k);
}
or their values:
for (var k in obj.alimenti[0]) {
console.log(obj.alimenti[0][k]);
}
You'd be better off parsing the JSON object and then extracting the string from the javascript object.
i.e var obj = JSON.parse("{\"date\": \" 9 Marzo\", \"time\": \" 07:00 - 13:20\", \"descrizione\": \" concerto\", \"alimenti\": { \"macchina\":\"si\", \"pollo\":\"no\" } }";);
console.log(obj.alimenti[0].macchina);
or pollo
console.log(obj.alimenti[0].pollo);
Also, that object structure is a little weird. You might want to remove the array from within the alimenti to better access the data.
Using response.alimenti[i][0] won't work because alimenti is an array of object(s), not an array of arrays.
This instead:
var alimenti = response.alimenti[0];
console.log(alimenti.maccina);
console.log(alimenti.pollo);
Example: http://jsfiddle.net/zcuwfb9s/
I have the following object
{
value: 20,
color:"#878BB6"
},
{
value : 40,
color : "#4ACAB4"
}
loaded from a text file abc.txt in my local directory in the server.
I want to convert this into an array object. I tried doing
var string = "{
value: 20,
color:"#878BB6"
},
{
value : 40,
color : "#4ACAB4"
}"
var array = JSON.parse("[" + string + "]");
alert(array);
Nothing happens unfortunately. Help appreciated !
You can use "eval" to accomplish what you are attempting.
var s = '{value: 20, color:"#878BB6" },' +
'{value : 40, color : "#4ACAB4"}';
var arr = eval('[' + s + ']');
alert(arr[0].value);
Also, in order for JSON.parse to parse it the string needs to be valid JSON. So you'll need to have quotes around the object property names. Like the following:
var s = '{"value": 20, "color":"#878BB6" },' +
'{"value": 40, "color": "#4ACAB4"}';
var arr2 = JSON.parse('[' + s + ']');
alert(arr2[1].value);
Although it would be better to modify the process for generating the text file to contain valid JSON if you can. Then you could use jQuery or some other method of just loading the JSON from the file directly.