Use a unicode string in JSON file as function parameter - javascript

I'm using the answer from this question to create random characters:
String.fromCharCode(0x30A0 + Math.random() * (0x30FF - 0x30A0 + 1));
I created a function with the same principle so I can change the first and the last character of the range:
function uni_char(first, last) {
var char = String.fromCharCode(first + Math.random() * (last - first + 1))
return char;
}
For example, if I run the function with 0x0000 and 0x007F as parameters, it works as expected. What I'm trying to do is to read a JSON file with multiple character ranges to use them with the function. This is the JSON:
[
{
"first": "0x0000",
"last": "0x007F"
},
{
"first": "0x0080",
"last": "0x00FF"
}
]
I populate an array with the JSON file data using the answer from this question:
var blocks = [];
$.ajax({
async: false,
url: '/scripts/data/blocks.json',
data: "",
accepts:'application/json',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
blocks.push(data[i]);
}
}
});
But when I use the values from the array with the function:
uni_char(blocks[0].first, blocks[0].last);
It just creates a � symbol. What am I missing? Maybe an encoding problem? Or a logic problem?

Related

Defining variables for JS lp-solver using an array

I'm trying to create a linear programing code in JS using lp-solver library, but I can't get the results to be outputted. It's probably because of incorrect model, because the results output for each product and "total cost" shows as undefined, so I'm guessing that the model doesn't work at all. The problem is that I'm not just inputting the variables by myself, but I fetch the products from a database (that is working correctly and I can output, for example, the first product's name as data[0]['name'] and it works just fine) so they are written in an array. I made a for loop trying to input the data of products into variables of the model, but I guess that is not working correctly or the problem is somewhere else in the model. May you please help me?
Part of code:
<script>
// Make an AJAX request to the PHP script that fetches the products and user's desired
calories from the database
$.ajax({
url: 'fetchProductsFromDatabase.php',
success: function(response) {
var data = response;
var userCalories = data[0]['userCalories'];
// Set up the model
var model = {
optimize: "price",
opType: "min",
constraints: {
"calories": {
equal: userCalories
},
},
variables: {
},
};
// Set up the variables and the constraints in the model
for (var i = 0; i < data.length; i++) {
model.variables[data[i]['name']] = { "price": data[i]['price'], "calories": data[i]
['calories'] };
model.constraints[data[i]['name']] = { equal: 0 };
}
// Solve the linear program
var result = solver.Solve(model);
Proof of "data" output. Written as console.log(data[0]['name/price/calories']);
Results of the code.
for (var i = 0; i < data.length; i++) {
console.log(data[i]['name'] + ': ' + result[data[i]['name']]);
}
console.log('Total cost: ' + result.price);

AJAX JSON response is returning the correct values, but also undefined values in between?

I'm working on some JavaScript code that is going to find the smallest unused number in a specified range of numbers. The AJAX request gathers all used numbers in the specified range, but is additionally returning undefined values in between the correct values? I've compared the returned values from the JSON response to what's currently in the SQL table and all the correct values are in both the JSON response and the SQL table, so I'm not sure where the undefined values are coming from.
https://imgur.com/a/rXLfEJk
JavaScript:
//Specified range of numbers to search.
var startRange = 40000;
var endRange = 49999;
//UPC's are padded with to 13 digits with 0's then sent as parameters.
var startUPC = '00000000' + startRange;
var endUPC = '00000000' + endRange;
// AJAX call to web API that gathers all UPC's within a range.
$.ajax({
url: "api/GetNewPLU",
type: "GET",
dataType: "json",
data: { 'startUPC': startUPC, 'endUPC': endUPC },
success: function (data) {
$.each(data.data, function (i, UPCs) {
for (var i in UPCs) {
console.log("UPC: " + UPCs[i].F01);
}
})
},
error: function (error) {
console.log(`Error ${error}`)
}
})
JSON Response:
{
"draw": null,
"data": [{
"DT_RowId": "row_0000000040002",
"OBJ_TAB": {
"F01": "0000000040002"
}
}, {
"DT_RowId": "row_0000000040008",
"OBJ_TAB": {
"F01": "0000000040008"
}
}, {
"DT_RowId": "row_0000000040013",
"OBJ_TAB": {
"F01": "0000000040013"
}
}, {
"DT_RowId": "row_0000000040017",
"OBJ_TAB": {
"F01": "0000000040017"
}
}
}
I plan to loop through the used numbers from the AJAX request comparing them to a sequentially incremented generated number until there is not a match and then save that unused number. I'm not sure if it's worth figuring out why I'm returning both values and undefined or if I should just find a way to filter out the undefined.
lodash _.difference can help to you.
Create two arrays. One for generated values, one for used values. And find diff between them.
var created = ["0000000040000", "0000000040001", "0000000040002"];
var used = ["0000000040001", "0000000040002"];
var unused = _.difference(created, used);

Javascript (Ajax) Parse JSON value

total javascript noob here. Just trying to get an understanding for the language.
I'm requesting a JSON request using the following code:
function request(){
$.ajax({
dataType: "jsonp",
type: 'GET',
url: "getWebsite",
success: function(result){
data = result;
$('.data').text(data);
console.log(data);
}});
The get request returns something like this:
"items": [
{
"topLevelComment": {
"authorDisplayName": "a"
"textDisplay": "b"
},
{
"topLevelComment": {
"authorDisplayName": "c"
"textDisplay": "d"
}
I would like to cycle through the AuthorDisplayName and textDisplay and randomly pick one from each. The best way to do this would probably be to put them both into arrays if I had to guess. I'm not sure how to even go about this.
var json={
"items": [{
"topLevelComment": {
"authorDisplayName": "a",
"textDisplay": "b"
}
}, {
"topLevelComment": {
"authorDisplayName": "c",
"textDisplay": "d"
}
}, {
"topLevelComment": {
"authorDisplayName": "e",
"textDisplay": "f"
}
}, {
"topLevelComment": {
"authorDisplayName": "g",
"textDisplay": "h"
}
}]
};
$("input:button").on("click",function(){
selectRand = Math.floor((Math.random() * json.items.length))
var r=json.items[selectRand].topLevelComment.textDisplay;
console.log(r);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="selectRand"/>
If your data is already in Object format, and you only want to get one from random pick. Then you don't have to loop for all the data. Just randomly select one index from your total data.
function request(){
$.ajax({
dataType: "jsonp",
type: 'GET',
url: "getWebsite",
success: function(result){
data = result;
$('.data').text(data);
console.log(data);
var randomIndex = Math.floor((Math.random() * data.items.length));
console.log("Selected data authorDisplayName: " + data.items[randomIndex].topLevelComment.authorDisplayName);
console.log("Selected data textDisplay: " + data.items[randomIndex].topLevelComment.textDisplay);
}
});
}
items is already an array. So you do the following:
Parse the result to json (Only if a string is returned)
items = JSON.parse(items)
Get a random index
let index = Math.floor((Math.random() * items.length))
Get the random data
let authorDisplayName = items[index].topLevelComment.authorDisplayName
let textDisplay = items[index].topLevelComment.textDisplay
As far as i understood you are trying to display a random object from the items array?
The items variable is already an array, so you don't need to create one. To get a random element of the array you can use the following code:
var item = result.items[Math.floor(Math.random()*items.length)];
I'm not sure where exactly the items array is located, let's say it's on the root of the result. You will probably also need to run the array through the method JSON.parse() to make it a valid JavaScript object.
And then to get the text and display name you can do this:
var authour = item.topLevelComment.authorDisplayName;
var text = item.topLevelComment.textDisplay;

Ignore case-sensitive input in an array?

I want to search a value in an array, but the search should ignore lower/upper-case letters.
How can I accomplish this?
This is my code:
$.ajax({
type: "GET",
url: "ajax.php",
dataType: "json",
data: { pageType: pageType, input: request.term, dataString: 'getPageInfo' },
success: function(data)
{
var values = $.map(data, function(item) { return {id: item.id, label: item.label, value: item.value}; });
for (var i = 0; i < values.length; i++) {
if (values[i].label.split(',').indexOf(request.term) >= 0) {
var found = values[i];
}
}
if (!found) values.push({id: 0, label: request.term + ' hinzufügen', value: request.term});
response(values);
It's about giving the option to create a new entry, if the input already matches an entry to prevent creating duplicate entries by the user as you can see in the last line. request.term is the value entered by the user and values is the array.
So for example, if I'm searching for "berlin" or "BERLIN" or "bERLiN" and the entry in my database is "Berlin", then it should still mark this item as found in the array.
One option would be to force things upper- or lower-case beforehand:
var iterm = request.term.toLowerCase();
// ...
if (values[i].label.toLowerCase().split(',').indexOf(iterm) >= 0) {
Alternately you could turn request.term into a case-insensitive regular expression, but doing so involves escaping all of the characters in it that might be special in regular expressions, which is a pain. You'd have to be looking through a lot of values for the toLowerCase overhead to make me want to look at that complexity.
Convert the values and term to lowercase:
if (values[i].label.toLowerCase().split(',').indexOf(request.term.toLowerCase()) >= 0) {
var found = values[i];
}

Jquery : Automatic type conversion during parse JSON

Is there a way to specify type while parsing Json, so that the conversion happens automatically.
So I have the jsonData, and the x and y values needs to be number. So, the only way I can think about is looping and converting each. Any better logic, or efficient way?
var jsonData = '[{"x:"1", "y":"2"}, {"x:"3", "y":"4"}]'
var needed = [{x:1, y:2}, {x:3, y:4}]
var vals = $.parseJSON(jsonData);
//
var Coord = function(x, y){
this.x = x;
this.y = y;
}
var result = [];
function convert(vals) {
for (var i=0,l=vals.length; i<l; i++) {
var d = vals[i];
result.push(new Coord(Number(d.x), Number(d.y)));
};
}
The JSON in the jsonData variable is not valid. Only the attribute should be inside of the double quotes. Whenever you convert data to JSON, use a parser (explained on json.org) and don't write it by hand. You can always check if JSON is valid by using tools like JSONLint.
Any number (integers, decimal, float) are valid JSON data types and doesn't have to be encapsulated with double quotes.
This is valid JSON: [{"x": 1, "y": 2}, {"x": 3, "y": 4}]
However, if you don't have control over the source and retrieve the JSON with ajax you can provide a callback function to the dataFilter option. If you're using jQuery 1.5 there's also converters which are generalized dataFilter callbacks.
I suspect that the x and y coords could be a decimal number which is why I chose to use parseFloat instead of parseInt in the examples below.
Example using a dataFilter callback function (pre jQuery 1.5):
$.ajax({
url: "/foo/",
dataFilter: function(data, type){
if (type == "json") {
var json = $.parseJSON(data);
$.each(json, function(i,o){
if (o.x) {
json[i].x = parseFloat(o.x);
}
if (o.y) {
json[i].y = parseFloat(o.y);
}
});
}
return data;
},
success: function(data){
// data should now have x and y as float numbers
}
});
Example using a converter (jQuery 1.5 or later):
$.ajaxSetup({
converters: {
"json jsoncoords": function(data) {
if (valid(data)) {
$.each(data, function(i,o){
if (o.x) {
data[i].x = parseFloat(o.x);
}
if (o.y) {
data[i].y = parseFloat(o.y);
}
});
return data;
} else {
throw exceptionObject;
}
}
}
});
$.ajax({
url: "/foo/",
dataType: "jsoncoords"
}).success(function(data){
// data should now have x and y as float numbers
});
The only way is to loop through you JSON data and convert the strings you find into numbers using parseInt("2");.
I had the same problem. In one line of code, I remove any quotes that are immediately before or after a numeral, or before a minus sign.
var chartData = $.parseJSON(rawData.replace(/"(-?\d)/g, "$1").replace(/(\d)"/g, "$1"));
In my case it was coming via AJAX from PHP code which I have control over, and I later found out I could simply use the JSON_NUMERIC_CHECK - see PHP json_encode encoding numbers as strings.
These solutions convert anything that looks like a number to a number. So if you can have something that looks like a number but needs to be treated as a string, you will need to go and figure out something else, depending on your data.
If you have control of the json source you can remove the quotes from the coordinates.
Acording to json.org, a value can be a sting, number, object, array, true, false, or null. A string is identified as a sequence of characters inclosed in douple quotes. A numeric value not contained in quotes should be interpeted as a number. You might to verify with the parser engine that is in use.
If your just consuming the json, the datafilter and converter methods, mention already, would be the most jquery way to solve the task.

Categories

Resources