Would this be a valid way of validating dot notation? - javascript

I'm building out a component that accepts an input of dot notation. I want to validate the input and when I stopped to think about "what is valid dot notation" I figured this would be a simple way of doing it, but it almost seems too simple so now I'm wondering if I'm missing something:
function isValidDotNotation(content: string) {
try {
content.split(".")
return true
} catch (exception) {
return false
}
}
So:
dot notation is a way of specifying a namespace within a json data structure then it seems like our main concern is validating keys
JSON requires strings for keys
the split static method hangs off of String so you'd only be able to fire it on a string
Specifying an array index in dot notation just makes the square brackets part of a string (e.g. in example.widgets[0].name, widgets[0] is still a valid string when .split()
A single level dot notation string can still be split into a single array value (e.g. "test".split(".") still works)
So when we fire split, as long as we don't throw an exception the the string given should be a valid dot notation. It may or may not lead you to anything within the json structure, but as far as a valid value it should be good, right?
Am I missing any nuance here? I've seen examples of people looping through the structure and stuff, but it seems like overkill to validate unless I'm missing something.

string.split will never throw an exception when passed a string. Therefore, via these rules, any string is valid dot notation. In that case you only need to verify whether something is a string, which you can do like so:
typeof content === 'string'

You're missing something. Your original code won't work with the input:
content1 = "example.widgets[.0].name"
content2 = "example.widgets[0].name."

Related

key of a JavaScript object must be a string

In JavaScript, if you type
typeof("2")
you should get string.
And if you type
typeof(2)
you should get number.
Now my question is, it is said that when you define an object, the key must be a string.
so this is legal
apple = {"color":"red"}
However, if I change the key to a number wrapped in the inverted commas, it should work as anything inside of inverted commas
apple={"2": "red"}
But If I call the object property, apple.2, this will fail with error Unexpected number.
so am just curious, what am I missing here while defining the objects in JavaScript.
An object key must be a string, but JavaScript allows you to assign an object with a number. It's just converted to a string behind the scenes, so:
apple = {2: "red"}
is the same as:
apple = {"2": "red"}
Using dot notation requires a valid identifier. So you can not access the property with apple.2 as 2 is a number, instead, you have to use bracket notation, either apple["2"] or apple[2].
Incidentally, there are other cases which can not be accessed with dot notation, such as:
apple = {"hyphenated-key": true}
Trying to access apple.hyphenated-key would not work, you have to use bracket notation as such apple["hyphenated-key"].

Jquery validate free emails using validator

I used jquery validator for validation.I have 50 free emails like(gmail.com, yahoo.com) so I need validate it.I chose an array then stored all the emails within an array.Below see my code there you could see I used the regular expression.I passed a variable in regular expression but it doesn't work for me.It threw the error like this SyntaxError: invalid range in character class
My code
$.validator.addMethod('nofreeemail', function (value) {
var emails = ["gmail.com","yahoo.com","hotmail.com"]
$.each(emails,function(i, val){
console.log("email", val)
var regex = new RegExp("/^([\w-.]+#(?!"+val+")([\w-]+.)+[\w-]{2,4})?$/");
console.log("regex", regex)
return regex.test(value);
});
}, 'Free email addresses are not allowed.');
I will post an answer since it is not evident here what is going on, but the underlying reasons are quite common.
You are using a constructor notation to define the regex. It is a correct approach when you need to build a pattern dynamically using a variable. However, a literal backslash must be written as "\\". All single backslashes are removed. Thus, you get an error since [\w-.] turns into [w-.] and it is an invalid character class. Also, the regex delimiters (those /..../ around the pattern) should never be used in the constructor notation unless you really need to match a string enclosed with /.
Besides, your emails contain non-word chars, and you need to escape them.
Use
var regex = new RegExp("^([\\w-.]+#(?!"+val.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')+")([\\w-]+\\.)+[\\w-]{2,4})?$");
I also believe the dot in ([\w-]+.)+ must be escaped, it is supposed to match a literal dot,

Accessing Javascript Object with Key

I have the following object self.originalData on the console:
However, when I try to access to first object in the array of originalData,
self.originalData[0hcMSJXljH]
getting the following error
the Uncaught>Syntax Error: Unexpected token ILLEGAL
I could not able to figure out where I am doing wrong.
You can use:
self.originalData["0hcMSJXljH"]
instead. Object keys are strings so if you use the [] notation, then you have to put a string or a variable that contains a string inside the brackets.
Your particular case is a bit unusual because usually, you can use the dot notation as in obj.property, but because your key starts with a number, it is not a legal identifier to use with the dot notation (you can't do self.originalData.0hcMSJXljH). So, you are forced to use the bracket notation with that particular key.
Try putting the key in quotes like this:
self.originalData['0hcMSJXljH']
You don't use quotes in your key, so it seems you are trying to use the variable identified by 0hcMSJXljH as the key. However, 0hcMSJXljH isn't a valid variable identifier, because it begins with a number, so your get an illegal-character error.
Simply use a string, not an identifier:
self.originalData["0hcMSJXljH"]
Have you tried
self.originalData["0hcMSJXljH"];
?
Otherwise:
self.originalData.0hcMSJXljH;
EDIT: last one not possible because the first char is a number, as explained to me
You must use quotes:
self.originalData['0hcMSJXljH']

Getting functions content with regex

I'm trying to get the functions from an input string by using regular expressions.
So far, I managed to get the JavaScript kind of function declarations with the following regex:
/(\b(f|F)unction(.*?)\((.*?)\)\s*\{)/g
Which when applied like this, will return me whole declaration on the first index:
var re = /(\b(f|F)unction(.*?)\((.*?)\)\s*\{)/g;
while ((m = re.exec(text)) !== null) {
//m[0] contains the function declaration
declarations.push(m[0]);
}
Now, I would like to get in the returned match, the whole content of each of the functions so I can work with it later on (removed it, wrap it...)
I haven't managed to find a regext to do so, so far, I got this:
(\b(f|F)unction(.*?)\((.*?)\)\s*\{)(.*?|\n)*\}
But of course, it catches the first closing bracket } instead of the one at the end of each of the functions.
Any idea of how to get the closing } of each function?
Any idea of how to get the closing } of each function?
This will be very hard with a regex. Because the function body can include any number of possibly nested brace pairs. And then consider strings containing unmatched braces in the function body.
To parse a non-regular language you need something more powerful than regular expressions: a parser for that language.
(Some regex variants have some ability to matched paired characters, but firstly JavaScript's regex engine isn't one; and secondly then there are those stringsā€¦.)

Parsing malformed JSON in JavaScript

Thanks for looking!
BACKGROUND
I am writing some front-end code that consumes a JSON service which is returning malformed JSON. Specifically, the keys are not surrounded with quotes:
{foo: "bar"}
I have NO CONTROL over the service, so I am correcting this like so:
var scrubbedJson = dirtyJson.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2": ');
This gives me well formed JSON:
{"foo": "bar"}
Problem
However, when I call JSON.parse(scrubbedJson), I still get an error. I suspect it may be because the entire JSON string is surrounded in double quotes but I am not sure.
UPDATE
This has been solved--the above code works fine. I had a rogue single quote in the body of the JSON that was returned. I got that out of there and everything now parses. Thanks.
Any help would be appreciated.
You can avoid using a regexp altogether and still output a JavaScript object from a malformed JSON string (keys without quotes, single quotes, etc), using this simple trick:
var jsonify = (function(div){
return function(json){
div.setAttribute('onclick', 'this.__json__ = ' + json);
div.click();
return div.__json__;
}
})(document.createElement('div'));
// Let's say you had a string like '{ one: 1 }' (malformed, a key without quotes)
// jsonify('{ one: 1 }') will output a good ol' JS object ;)
Here's a demo: http://codepen.io/csuwldcat/pen/dfzsu (open your console)
something like this may help to repair the json ..
$str='{foo:"bar"}';
echo preg_replace('/({)([a-zA-Z0-9]+)(:)/','$1"$2"${3}',$str);
Output:
{"foo":"bar"}
EDIT:
var str='{foo:"bar"}';
str.replace(/({)([a-zA-Z0-9]+)(:)/,'$1"$2"$3')
There is a project that takes care of all kinds of invalid cases in JSON https://github.com/freethenation/durable-json-lint
I was trying to solve the same problem using a regEx in Javascript. I have an app written for Node.js to parse incoming JSON, but wanted a "relaxed" version of the parser (see following comments), since it is inconvenient to put quotes around every key (name). Here is my solution:
var objKeysRegex = /({|,)(?:\s*)(?:')?([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*)(?:')?(?:\s*):/g;// look for object names
var newQuotedKeysString = originalString.replace(objKeysRegex, "$1\"$2\":");// all object names should be double quoted
var newObject = JSON.parse(newQuotedKeysString);
Here's a breakdown of the regEx:
({|,) looks for the beginning of the object, a { for flat objects or , for embedded objects.
(?:\s*) finds but does not remember white space
(?:')? finds but does not remember a single quote (to be replaced by a double quote later). There will be either zero or one of these.
([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*) is the name (or key). Starts with any letter, underscore, $, or dot, followed by zero or more alpha-numeric characters or underscores or dashes or dots or $.
the last character : is what delimits the name of the object from the value.
Now we can use replace() with some dressing to get our newly quoted keys:
originalString.replace(objKeysRegex, "$1\"$2\":")
where the $1 is either { or , depending on whether the object was embedded in another object. \" adds a double quote. $2 is the name. \" another double quote. and finally : finishes it off.
Test it out with
{keyOne: "value1", $keyTwo: "value 2", key-3:{key4:18.34}}
output:
{"keyOne": "value1","$keyTwo": "value 2","key-3":{"key4":18.34}}
Some comments:
I have not tested this method for speed, but from what I gather by reading some of these entries is that using a regex is faster than eval()
For my application, I'm limiting the characters that names are allowed to have with ([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*) for my 'relaxed' version JSON parser. If you wanted to allow more characters in names (you can do that and still be valid), you could instead use ([^'":]+) to mean anything other than double or single quotes or a colon. You can have all sorts of stuff in here with this expression, so be careful.
One shortcoming is that this method actually changes the original incoming data (but I think that's what you wanted?). You could program around that to mitigate this issue - depends on your needs and resources available.
Hope this helps.
-John L.
How about?
function fixJson(json) {
var tempString, tempJson, output;
tempString = JSON.stringify(json);
tempJson = JSON.parse(tempString);
output = JSON.stringify(tempJson);
return output;
}

Categories

Resources