Unable to access JSON property with "-" dash [duplicate] - javascript

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
How do I reference a JavaScript object property with a hyphen in it?
(11 answers)
Closed 3 months ago.
I am unable to retrieve a value from a json object when the string has a dash character:
{
"profile-id":1234, "user_id":6789
}
If I try to reference the parsed jsonObj.profile-id it returns ReferenceError: "id" is not defined but jsonObj.user_id will return 6789
I don't have a way to modify the values being returned by the external api call and trying to parse the returned string in order to remove dashes will ruin urls, etc., that are passed as well. Help?

jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).
To access a key that contains characters that cannot appear in an identifier, use brackets:
jsonObj["profile-id"]

In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax
This is the wrong way
json.first.second.third['comment']
and will will give you the 'undefined' error.
This is the correct way
json['first']['second']['third']['comment']

For ansible, and using hyphen, this worked for me:
- name: free-ud-ssd-space-in-percent
debug:
var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]

For anyone trying to apply the accepted solution to HomeAssistant value templates, you must use single quotes if you are nesting in doubles:
value_template: "{{ value_json['internet-computer'].usd }}"

If you are in Linux, try using the following template to print JSON value which contains dashes '-'
jq '.["value-with-dash"]'
It worked for me.

Related

Javascript Object attribute with '-' doesn't work properly [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 7 years ago.
I have a JSON response in the following format.
{
"_meta" : {
"next-person-id" : "1001",
"totalPersons" : "1000"
}
}
I am using Angular's $http service to retrieve this and trying to access next-person-id attribute in javascript like the following,
$http.get(url).then(
function(response){
console.log(response._meta.next-person-id);
}
);
But the next-person-id in the response is undefined always. But I'm able to access totalPersons attribute. Is there any problem with getting attributes with '-' character in javascript?
Use bracket notation:
console.log(response._meta['next-person-id']);
A possible alternative is to change the keys to use underscores, so that _meta.next_person_id would work.
You cant write variables using - as it is also a minus sign.
To solve this, use square bracket notation:
console.log(response._meta['next-person-id']);
Yep true, because in JavaScript you can use Latin letters, numbers and $ _ symbols for variables or properties.
If you want to use -, you should escape it with string quotes.
like this
var obj = {
'next-person-id': 2
}
console.log(obj['next-person-id']); // 2
Explanation:
In Global scope - means minus. It tries to subtract person from name. So you will get an error like this:
ReferenceError: name is not defined
In JS you can access to object property in 2 ways
1) Dot nation
obj.property
2) Square bracket nation
obj['property']
Here you need to parse string, so as you know in string you can have any symbols except string quote symbol (it will close the string)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation

Javascript eval fails on complicated json array [duplicate]

This question already has answers here:
JSON Javascript escape
(4 answers)
Closed 7 years ago.
I want to convert a json string to object by eval, but it fails with error like:
Uncaught SyntaxError: Unexpected identifier VM250:1
below is my string:
'[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';
Seems there is something wrong in the bold part, but i don't know how to fix it
The code below is not working
var m='[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';
eval(m);
The code below is working so i think the data structure of this json string is ok
var m=[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}];
alert(m[0].option_in_json);
Also tried with $.parseJSON with no luck
It does not work because you are not escaping the data inside the string literal correctly. Look at the value of m in the first case, especially the quotation marks:
[{"option_in_json":"[{"option":"1","is_answer":false}]","question":"1+1"}]
// ^ ^
I removed some irrelevant data. You should be able to see that this cannot be valid JavaScript (or JSON), because the quotation mark before option terminates the string.
In order to put the data inside a string literal, you should either fix the data so that it doesn't contain nested JSON, or escape \:
'[{"option_in_json":"[{\\"option\\": ... }]"}]'
Better of course if you are not putting it in a string literal in the first place.
var m='[{"quiz_id":"3","_id":"1","option_in_json": [{"option":"1","is_answer":false},{"option":"2","is_answer":true}],"question":"1+1"}]';
// ^-- don't wrap in "" so no need to escape inner double quotes.
console.dir(JSON.parse(m));

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/

Javascript object property quotes [duplicate]

This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 5 years ago.
Let's say I have the following object:
var VariableName = {
firstProperty: 1,
secondProperty: 2
}
Do I have to wrap the object properties in quotes like this?
var VariableName = {
'firstProperty': 1,
'secondProperty': 2
}
Is this Single quotes in JavaScript object literal the correct answer?
No, you don't need to do that.
The only reasons to quote object-keys are
the property name is reserved/used by the browser/js engine (eg. "class" in IE)
you have special characters or white spaces in your key
so for instance
var VariableName = {
"some-prop": 42, // needs quotation because of `-`
"class": 'foobar' // doesn't syntatically require quotes, but it will fail on some IEs
valid: 'yay' // no quotes required
};
You only have to use the quotes around the property, if the property name is a reserved word (like for, in, function, ...). That way you prevent Javascript from trying to interpret the keyword as a part of the language and most probably get a syntax error.
Furthermore, if you want to use spaces in property names, you also have to use quotes.
If your property names are just normal names without any collusion potential or spaces, you may use the syntax you prefer.
One other possibility that requires quotes is the use of Javascript minifiers like google closure compiler, as it tends to replace all property names. If you put your property names in quotes, however, the closure compiler preserves the property as you coded it. This has some relevance when exporting objects in a library or using an parameter object.
Property names in object literals must be strings, numbers or identifiers. If the name is a valid identifier, then you don't need quotes, otherwise they follow the same rules as strings.
firstProperty and secondProperty are both valid identifiers, so you don't need quotes.
See page 65 of the specification for more details.
For Javascript you usually do not have to use quotes. You may use ' or " if you like, and you must use quotes if there is a clash between the name of your property and a JS reserved word like null. The answer you linked to seems to be correct, yes.
For JSON, you should use " around strings (including object property names)

Why do we need to add parentheses to eval JSON? [duplicate]

This question already has answers here:
Why does JavaScript's eval need parentheses to eval JSON data?
(7 answers)
Closed 8 years ago.
Why does the following code needs to add ( and ) for eval?
var strJson = eval("(" + $("#status").val().replace(";","") + ")");
PS: $("#status").val() is returning something like {"10000048":"1","25000175":"2","25000268":"3"};
It depends what the value in that element is (an unknown), wrapping it in () is the safe route to account for possibly of no input being there.
Edit: Now that you've cleared up it's JSON, this isn't valid:
eval('{"10000048":"1","25000175":"2","25000268":"3"}');
But this will result in a valid object being returned:
eval('({"10000048":"1","25000175":"2","25000268":"3"})');
//effectively:
eval('return {"10000048":"1","25000175":"2","25000268":"3"};');
Picture in a JavaScript file:
<script type="text/javascript">
{"10000048":"1","25000175":"2","25000268":"3"}
</script>
This is going to fail, it's just an object declared inline but not proper syntax...the same reason a server has to support JSONP for it to work.
A bit tangential to the question, but since you're including jQuery, you might as well use $.parseJSON() (which will use the native JSON.parse() if available) for this:
var strJson = $.parseJSON($("#status").val().replace(";",""));
eval takes a JavaScript statement or expression, but {...} would be valid as a statement or an expression, and the grammar of JavaScript prefers a statement.
As an expression:
{"10000048":"1","25000175":"2","25000268":"3"}
is an Object with some properties (what you want).
As a statement, it is a block:
{ // begin Block
"10000048": // LabelledStatement (but the quotes are invalid)
"1", // Expression, calculate string "1" then discard it, then
"25000175": // you can't put a label inside an expression
which gives an error.
(JavaScript labels can be used to label a particular statement for use with break/continue. They're a bit pointless and almost never used.)
So by adding the parentheses you resolve the ambiguity. Only an expression can start with (, so the contents are parsed in an expression context, giving an object literal, not a statement context.
Incidentally this is not quite enough to correctly interpret all possible JSON values. Due to an oversight in JSON's design, the characters U+2028 and U+2029, two obscure Unicode line-ending characters, are valid to put unescaped in a JSON string literal, but not in a JavaScript string literal. If you want to be safe, you can escape them, eg:
function parseJSON(s) {
if ('JSON' in window) return JSON.parse(s);
return eval('('+s.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')+')');
}

Categories

Resources