I am trying to find a way to solve a weird property issue serve by server . For some reason server have to send some property in format like propertyname[] so when I have to get the value of the property containing [] is giving me parsing errors
propertyname[] is an array
{{#if this.propertyname[].length}}
...some stuff in here
{{/if}}
there is no way I can read this weird property or maybe I am missing some basic thing in here . any suggestion will be appreciated.
Actually handlebars allows you reference a property that is not a valid identifier such as ! [ # # + * -, just use segment-literal notation to access a invalid property:
this.[propertyname{}] // it equals to this['propertyname{}']
Unfortunately, this method works on the premise that you don't use ']' in a path literal.
I think that change the property name (maybe use other character) or updated the data structure in the front end are possible way to solve this problem.
Related
I'm developing custom field plugin for Jira Cloud in React.
I have a variable cfDate1 which is stores custom field id as a string like customfield_10072.
So I want to reach the time data inside my custom field id.
Let's say my data is in jsonData variable.
I try to reach with jsonData.fields.[cfDate1] but I get Error: Identifier expected.
I searched a few but I think I couldn't find the right keywords to get some solutions.
Is there anyone can help me to figure it out. I need to learn how to reach json data in my json query with a string variable. Thanks already!
JSON Format (jsonData):
{
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations,customfield_10010.requestTypePractice",
"id": "10008",
"self": "https://alimert.atlassian.net/rest/api/2/issue/10008",
"key": "SP-1",
"fields": {
"statuscategorychangedate": "2021-10-11T12:17:41.291+0300",
"customfield_10072": "2021-01-13T02:00:00.000+0300",
"customfield_10073": "2021-01-26T06:30:00.000+0300",
"customfield_10075": "2021-10-14",
"customfield_10076": "2021-10-15" }
It has to be jsonData.fields[cfDate1] and not jsonData.fields.[cfDate1].
There are four ways to access a property of an object1:
Syntax
Dynamickey
Optionalchaining
.
[]
?
Equivalents2
obj.xyz
No
No
Yes
No
No
obj['xyz']
obj[key]
Yes
No
No
Yes
No
-
obj?.xyz
No
Yes
Yes
No
Yes
obj == null ? obj.xyz : undefinedobj == null ? obj['xyz'] : undefined
obj?.[key] ⚠️
Yes
Yes
Yes ⚠️
Yes
Yes
obj == null ? obj[key] : undefined
As you can see in this table, in most cases you use either . (for static keys) or [] (for dynamic keys).
Optional chaining adds a ?. However, in the case of optional chaining and a dynamic key, the possibly unexpected syntax of ?.[] is used which has both . and []3. Note that this is only the case with optional chaining - without optional chaining, the syntax .[] is not valid.
1: There is also Reflect.get(obj, key), and you could stretch that definition to count something involving walking the prototype chain, calling Object.getOwnPropertyDescriptor and accessing value or get as well, if you really wanted to. But for a beginner, these would be, if anything, more of academic interest and rather confusing to include in a list of property access methods for everyday use.
2: For optional chaining, the shown equivalents only apply to the case of no further level of chaining (e.g. obj?.xyz but not obj?.xyz.abc). An additional - quite useful - property of the optional chaining operator is that it stops evaluation of the rest of the expression entirely in case the left-hand side is nullish, so that you can write obj?.xyz.abc instead of obj?.xyz?.abc without an error Cannot read properties of undefined (reading "abc"). With the shown equivalent that wouldn't work.
3: The reason for this slightly awkward syntax is that optional chaining was added to the language only recently, and ?[] couldn't have been used due to ambiguity with the ternary operator and added difficulty in writing parsers to handle this situation. The same goes for ?.(). See FAQ in the optional chaining proposal for more information.
This seems to be very silly to me but I am having this problem. Can anybody help me with this.
So, I have an API that I am fetching some data and seems that the API response has a data format like this:
start-time:2323232
end-time:2332323
Now, when in my react rendering component, I am trying to display the data like this:
{data.start-time}
I am actually getting an error saying that time is undefined. Are there any rules that we cannot read/display data in JSX with - separator or something like that. Or, Does anybody know how can I solve that problem. Any helps would be highly appreciated.
You cannot use start-time as an identifier. you need to use square brackets to access the property in this case
data["start-time"]
For further reference Object property accessors
You can only use the dot notation if the property name is a valid JavaScript identifier.
In JavaScript, identifiers are case-sensitive and can contain Unicode letters, $, _, and digits (0-9), but may not start with a digit.
Properties that are not valid identifiers must be accessed through the bracket notation.
const data = { name: "stopwatch", "start-time": 2323232, "end-time": 2332323 };
console.log(data.name); // <- valid identifier
console.log(data["start-time"]); // <- invalid identifier
var jsonString = '{"DeviceId":3,"results":{"1":"[{\"x\":513,\"y\":565,\"width\":175,\"hight\":208}]"}}';
var message = JSON.parse(jsonString);
I got an error saying Unexpected token u in JSON at position 0
at JSON.parse.
Could you please guide me what's wrong?
THanks in advance!
At the last few characters looks wrong. The :212 has no sense as the value (that long array) for key "1" was already set, so that later :212 looks weird
Also enclosing it in single quotes it makes that all be like a huge string, and not as an array structure.
See Results key as value contains a sub array which contain "1" key which as value contains a string enclosing another json array (but escaped as plain string, so no structurally accesible for the main object . But that string if post -processed the :212 is paired to what? , no key, no comma neighter , to the precedent whole array which already was the value, not the key?. Anyway weird.
In your JSON string, there is wrong something with ":212", as it's not valid JSON, because it doesn't have any property that it's mapping the value for. For example, you are mapping values for width and height with properties keys. But for "212", there is no property.
Here is the above JSON formatted:
var jsonString = '{"DeviceId":"3","results":{"1":"[{\\"x\\":513,\\"y\\":565,\\"width\\":175,\\"hight\\":208}]"}}'
var message = JSON.parse(jsonString);
If you want to format the results, you can do to it, there is no error on it:
JSON.parse(message.results['1'])
Here is the JS Bin link for above code: https://jsbin.com/fiyeyet/edit?js,console
Just an advice
Professional code is all about proper spacing, proper identation , proper commenting, don't try to write down all within one single line, structure it VISUALLY nice to see nice to read nice to comprehend, and you will be approved in most jobs.
Hint: declare a normal array/object , convert it to json string using the proper function, then use the string variable returned by the function to test your code or whatever doing. That way, you can write down in the source really nice the structure.
In my component template, I'm getting output as [output:Output] but not what I wanted. I'm sending an object from a parent container using #Output
In my template when I try to bind {{selectedMovDetail|json}} the output is { "name": "The Walking Dead","rating":"8.6"}
But when I try to extract data using {{selectedMovDetail['name']}} I get the following error
When I tried to debug with Augury (chrome debug tool) I get
Now I'm confused how to extract the object values.
Any help regarding this is much appreciated
Use: selectedMovDetail?.name instead of selectedMovDetail['name'].
When you use the "elvis" operator, ?, in selecting your json keys, it will not throw an error if it can't find a specific key or the value has not been loaded yet (only in html).
For example in your case: selectedMovDetail.name exists after the template has been viewed so using ? before the . makes sure that name will be printed when it's loaded.
IN my web service,I return one json object in the method:
{name:'xx'}
I use the ajax to send the request,then parse them using the 'eval'
onComplete:function(req){
var data=eval(req.responseText);
//do something according data
}
However,I can not get the 'data'.
When I retrun the following string:
[{name:'xx'}]
It worked,and I get the 'data' as an array.
Through google,I know that it is caused by the '{' in the return string.
So I wonder if there is no way to retrun a json object ?
Use JSON.parse or jquery's $.parseJSON - if you use jquery - instead of eval.
Also, if you do use jquery, you can take advantage of the built-in ajax method that automaticly retrieves and parses the response as a json object : $.getJson.
If you still don't want to modify your "logic", you can try to eval your response with added brackets : var data = eval('(' + req.responseText + ')');
Have a read of this blog post on JSON hijacking. The author explains the issue your running into
You might have seen code like the following when related to JSON:
eval('('+JSON_DATA+')');
Notice the beginning and ending parenthesis, this is to force
JavaScript to execute the data as an object not a block statement
mentioned above. If JavaScript did attempt to execute JSON data
without the parenthesis and the JSON data did in fact begin with “{”
then a syntax error would occur because the block statement would be
invalid.
...more info on why...
Rather than adding () around your JSON response, you should be using JSON.parse or $.parseJSON like gion_13 has said. Eval isn't the way to go.
Also, like quentin said in the comments, you need to change the JSON you're returning as it's invalid. You need to quote your key as well as your value.
It worked,and I get the 'data' as an array.
That's what it's supposed to do. [] is the syntax for declaring an array. If you want the inner object, then just return {name: 'XX'}.