string to JSON parse , javascript runtime invalid character - javascript

I am trying to read the values of properties in this string, when i try to parse it , i get invalid character. Can you tell me whats wrong here
data = [{'title' : 'location 1','lat' : '29.769730','lng' : '-95.257181','desc' : 'Apartments',},{'title' : 'location 2','lat' : '29.852264','lng' : '-95.469999','desc' : 'location description',},];
var test = $.parseJSON(data)l
error - Unhandled exception at line 138, column 13 in http://localhost:17765/Loc/index
0x800a03f6 - JavaScript runtime error: Invalid character

In your code, data is not a string. It is an array. It does not need parsing (other than by the JavaScript compiler). Just discard $.parseJSON and work with the data.
data = [{'title' : 'location 1','lat' : '29.769730','lng' : '-95.257181','desc' : 'Apartments',},{'title' : 'location 2','lat' : '29.852264','lng' : '-95.469999','desc' : 'location description',},];
data.forEach(o => console.log(o.title));
It is being returned from an mvc5 controller method as a string
If your code does not accurately reflect the data you have and you do have a string, then it would need parsing.
The code you provided is, however, not valid JSON which:
Requires strings be quoted with " not '
Does not allow trailing , after the last item in an array.
You need to fix the server side code so it returns real JSON.
This will probably involve replacing some code which attempts to generate JSON by mashing together strings with some which uses a JSON aware library function (see this question).

Your JSON is invalid, try this:
var data = '[{"title" : "location 1","lat" : "29.769730","lng" : "-95.257181","desc" : "Apartments"},{"title" : "location 2","lat" : "29.852264","lng" : "-95.469999","desc" : "location description"}]';
var test = $.parseJSON(data);
validate your JSON here
[{"title" : "location 1","lat" : "29.769730","lng" : "-95.257181","desc" : "Apartments"},{"title" : "location 2","lat" : "29.852264","lng" : "-95.469999","desc" : "location description"}]

Related

How to replace Schema «availability» string with multiple values?

I am noob with structured data implementation and don't have any code knowledge. I have been looking for a week how to solve my problem with "availability" in Google structured data testing tool.
My stocks on the front have 3 possibilities :
"Stock : 1234" (text + stock numbers)
"Stock : Coming soon"
"Stock : On demand"
Google Results example
But he problem is Goggle accept only in my case "InStock" or "OutOfStock"
I have a CSS variable element #PdtXQStock named in a variable "Product-stock"
How can have :
if "availability" string contain numbers (not is number) ==> output "InStock"
if "availability" string is "Stock : Coming soon" ==> output "OutOfStock"
if "availability" string is "Stock : On demand" ==> output "InStock"
What is the proper Custom Js function from beginning to end?
function(){
var string = {{Product-stock}};
string = "https://schema.org/InStock";
string = string.replace(/Stock : Coming Soon/g, "OutOfStock");
string = string.replace(/Stock : On demand/g, "InStock");
return string.replace;
}

Angular split string to array

I have a String message like that :
messages = "Line 249 : Validation error, Line 287 : Validation error"
I want to split this message like this :
messages [] = [ { position: 1, message: 'Line 249 : Validation error' },
{ position: 2, message: 'Line 287 : Validation error' }]
Could you please help with this thank you.
The easiest way to turn a string into an array of objects is to first split the string using the delimiter, which in this case is the comma, so start with.
const test = "Line 249 : Validation error, Line 287 : Validation error";
const parts = test.split(",");
Then, you want to use the map array function to return an object for each part that's been split. The es6 map function has a callback that returns the piece of the array and the index in which it was found. you don't want the index, but rather an ordinal (per your example above)
Here's what i would do:
const test = "Line 249 : Validation error, Line 287 : Validation error";
const parts = test.split(",").map((text, index) => {
return {
position: index+1,
message: text.trim()
}
});
Now, the parts variable holds an array of objects that matches your required output
I think your error message can be split into an array using javascript split method.
so
messages = message.split(',')
will do the magic
But to add your position,
let messages = "Line 249 : Validation error, Line 287 : Validation error"
messages= messages.split(',').map((x,index)=>{
let obj ={}
obj.position=index+1;
obj.message = x
return obj;
});
console.log( messages )

Problem with timestamp formats in .find() in nodejs/express/Mongoose js

I have a collection like this;
{
"_id" : ObjectId("5d428c8b0edc602c155929c5"),
"source" : "connection",
"class" : "dns",
"ts" : 1503528301.909886,
"uid" : "C8avTr2cLyrJJxkN9",
}
If I print the key and type of key in mongo shell, I can see that ts actually is a string:
ts string
When I receive a query, I need to get the ts value from the URL and do a .find() query.
GET http://localhost:3300/alerts?ts=1503528332.909886&limit=100&page=1
startTs = req.query.ts
This may have to be converted to a ts without the '.' after the second. I have looked at converting 1503528332.909886 to float, multiply by 1000 1503528332909.886 and truncate to integer 1503528332909. I have also tried using both string and number format.
results.results = await model
.find({"ts": {"$gte": <ts_variable: what format do I use?> }})
.skip(startIndex)
.exec();
res.paginatedResults = results;
If I only use ".find({})" and not try to select based on ts, everything works as expected. Appreciate any tips you have.

String replace regex invalid quantifier in js/GAS

Based on https://www.plivo.com/blog/Send-templatized-SMS-from-a-Google-spreadsheet-using-Plivo-SMS-API/ I have the following code:
function createMessage(){
data = {
"SOURCE" : "+1234567890",
"DESTINATION" : "+2345678901",
"FIRST_NAME" : "Jane",
"LAST_NAME" : "Doe",
"COUPON" : "DUMMY20",
"STORE" : "PLIVO",
"DISCOUNT" : "20",
}
template_data = "Hi , your coupon code for discount of % purchase at is "
Logger.log(data);
for (var key in data) {
Logger.log(key);
if (data.hasOwnProperty(key)) {
template_data = template_data.replace(new RegExp('+key+', 'gi'),data[key]); // error here
}
}
Logger.log(template_data);
return template_data;
}
When I run createMessage I get :
SyntaxError: Invalid quantifier +. (line 57, file "Code")
From a previous question and if I understand correctly the loop goes through each key, value pair looking for all matches of the key (g) in a case insensitive fashion (i).
I don't understand the pattern '+key+' This causes the error and my attempts to test patterns like '+SOURCE+' also give the same error, although the seem to work while testing at https://regex101.com/r/CF967t/2 .
Can someone give me an explanation of the problem
sign + usually is a repetition operator, and causes the preceding token to repeat one or more times key+ would be expressed as keykey*
You have pass only key
template_data = template_data.replace(new RegExp(key, 'gi'),data[key]);

Parse a JS script using PHP and REGEX to get a JS variable value

I need to open a JS file from PHP, to find a json var in this file, and convert it to a php array.
Right now I can't figure out which regex to use.
// get the js file
$file = file_get_contents ("http://pve.proxmox.com/pve2-api-doc/apidoc.js");
// extract the json content of var pveapi
if ( preg_match ( "#pveapi = ({[^}]*})#", $file, $infoJson ) ) {
$arrJson = json_decode ( $infoJson [1], true );
}
// shows nothing so far :((
print_r($arrJson);
I have found few examples to do that, but none would work for me. Anyone with decent skills in regex could help me please ?
Ben
edit: added a part of the js file :
var pveapi = [
{
"info" : {
"GET" : {
"parameters" : {
"additionalProperties" : 0
},
"permissions" : {
"user" : "all"
},
"returns" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {}
},
"links" : [
{
"rel" : "child",
"href" : "{name}"
}
]
},
"name" : "index",
"method" : "GET",
"description" : "Cluster index."
}
}
}
];
Ext.onReady(function() { ... }
In this case, the end can be found by matching a semicolon at the end of a line:
if (preg_match('/^var pveapi = (.*?);$/ms', $js, $matches)) {
$data = json_decode($matches[1]);
print_r($data);
}
Per default the RegEx engine operates greedily on individual lines, so you'd have to tell it to do the opposite – the RegEx you seem to be looking for would be
#\spveapi\s*=\s*(.*?);\s*$#s
What it does is:
#
Start the expression
\s
Make sure the variable name is preceded by whitespace, so it's not part of a different variable name
pveapi
Find the variable
\s*=\s*
Make sure there's an equal sign with optional whitespace around it
(.*?);\s*$
Get as few characters as possible before finding a semicolon – i.e. all characters until the first semicolon that is follow only by optional whitespace and a line ending
#ms
End the expression and tell it to let . match line endings too and match $ to the ending of each line

Categories

Resources