Accessing Javascript Object with Key - javascript

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']

Related

Would this be a valid way of validating dot notation?

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."

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"].

JS/Nodejs can't access quoted index of object

I use babyparse (PapaParse) in nodejs to process csv to javascript objects.
One object output is as follows:
{ 'ProductName': 'Nike t-shirt',
ProductPrice: '14.99',
ProductPriceOld: '39.99' }
You can see that somehow the first index is quoted ('ProductName').
I can't manage to access this value. I have tried:
console.log(product['ProductName'])
console.log(product["\'ProductName\'"])
console.log(product['\'ProductName\''])
console.log(product.ProductName)
This all results in 'undefined'. product.ProductPrice or product['ProductPrice'] gives me the correct value.
Any idea what can be causing this, and how to solve it?
Edit: if I JSON.stringify(product) the single quotes are gone, but if I JSON.parse(json) into the object, the single quotes return..?
The reason that the property name is expressed as a string instead of an identifier in the output is that the name includes characters which aren't allowed in an identifier.
Specifically, the first character is: U+FEFF : ZERO WIDTH NO-BREAK SPACE [ZWNBSP] (alias BYTE ORDER MARK [BOM]).
You need to include that in the property name when you access it.
product["\uFEFFProductName"]

Issue in accessing JSON object?

Am facing issue in accessing the JSON object :
JSON Object am receiving is :
{"71":"Heart XXX","76":"No Heart YYYY"}
I tried to get the value of 71 and 72 separately and use it ...
but am getting some compile time issue as :
Syntax error on token ".71", delete this token
Code:
var map=$("#jsonText").val();
alert(map);
var obj=jQuery.parseJSON(map);
alert("JSON ::"+obj.71);
If am printing obj , am able to view [Object Object]
Can any one out there please help me to find the mistake i did ..I know the question above is asked in many threads in SO . Below are the few threads i found , but failed when i attempted to implement it ..
jquery json parsing
Also tried using the Jquery tutorial given in
Jquery JSON
Its working fine if the key is a String but getting the above error if its a number ...
Try this:
alert("JSON ::" + obj[71]);
"71" isn't a valid property identifier: an identifier should start with a letter, the underscore or the dollar sign. You can avoid this problem using square brackets instead.
Note: everything that's put between square brackets is converted into strings. Even functions, DOM elements or regular expressions: they're all converted with their toString methods, or their superclass' toString.
So 71 there is converted into "71". If you want a little more performance you can directly use the latter. If you don't need it, you can cut some key presses with just 71.
Use instead
alert("JSON ::"+obj["71"]);
according to the rules or javascript a identifier should not start by a number so if it starts by a number or for that matter contains spaces and other special charcters then you should access it by using the [] operator and not by . operator
so obj.71 is invalid but obj["71"] is
try using this site:
http://json.parser.online.fr/

parsing JSON using javascript gives me undefined while getting the value from the json response

i am parsing an json string usin javascript
{
"head": {
"example": "0"
},
"res": {
"#test": "121",
"#found": "5"
}
}
i am getting the http response from the remote site and i am using javascript to extract the #found value .i used the below code .
var json=eval('('+request.responseText+')');
alert(json.head.res.#found);
gives me a null value can u please tell me how can i parse this.
alert(json.head.res['#found']);
# is not valid to start a variable name, so you have to use bracket notation. Or change the variable name to be valid.
Basically, in regular expression form: [a-zA-Z_$][0-9a-zA-Z_$]*. In
other words, the first character can be a letter or _ or $, and the
other characters can be letters or _ or $ or numbers.
What characters are valid for JavaScript variable names?
Per Topera's answer head and res are on the same level in your object not nested.
Attribute "res" is not inside "head" attribute.
Try this: json.res['#found']
Try json.res['#found']. JavaScript object properties that are not valid variable names cannot be accessed using dot notation. Also, as noted by others, #found is not in head.
fix these 3 things :
# is not a valid variable name character. you should consider the [] syntax instead of the "dot" one.
res is not in head.
please don't use eval. I strongly advise you to use JSON.parse instead of eval
var json = JSON.parse(request.responseText);
alert(json.res['#found']);
alert(json.res['#found']);
res is not inside head.

Categories

Resources