Parsing JSON with spaces in key name with AngularJS - javascript

I have a json which has spaces in key names.
The JSON has the following format
{
"response":{"docs":[
{
"my name":"krammer",
"job": "stackexchange"
}
}
}
While using ng-repeat to get the parameters into a list, I use the following code
{{friends.['my name']}}
But this gives an empty output. While
friends.my name
gives an error.
So how can the key names with empty spaces be accessed using AngularJS ?

Please try this
{{friends['my name']}}

It doesn't have anything to do with angular, this is the way we read props from JavaScript object, here you have a object called friends. so these are all we can do, if we don't have invalid javascript characters for naming in JavaScript, like space and some other:
friends.myname
friends['myname']
friends["myname"]
but when we have those invalid characters we only can do:
friends['my name']
friends["my name"]

You may run into a case where {{friends['my name']}} does not work. If so, try the following:
{{friends.my_name}}

{{friends['my name']}} will be working fine

Related

JSON.parse() fails when a string contains the "null" substring... for example with italian words like "annullo" or "annullare"

Good morning everyone and thank you in advance for any suggestions. I have written a small web application to perform simple searches in a stamps database using php and javascript.
The server sends to the browser the whole database as a JSON and the queries are done client-side with a javascript code.
The JSON has this structure:
{"ck":0,"db":[["string11","string12","string13"],["string21","string22","string23"], etc... } .
Until now the system has worked perfectly and over 1500 stamps could be shown.
Suddenly it stopped working and, in the browser's Javascript console, this error message appeared:
VM672:1 Uncaught SyntaxError: Expected ',' or ']' after array element in JSON at position 97506 at JSON.parse (<anonymous>) ...etc...
After a series of tests, by exclusion I came to discover that it was the word "annullo" in the last added record to generate the error.
I guess it could be the substring "null" to give problems, but I have no idea how to escape it.
A really strange thing is that, whilst failing with the JSON.parse() function, browser's javascript console, as well as other json validation tools, recognise the server's response as a valid JSON.
Thanks for any help!
As #Andrea Soffiantini pointed in a comment, this was the actual problem:
Client side I had this command a few lines before parsing: data = data.replaceAll("null","\"\""); , where data is the json as a string, as received from server.
This replaces the string "anullo" with "a""o", which is invalid in JSON syntax.
I think I understand the problem. All strings are enclosed in quotes.
{example: "example"}
In the development of this case they must have put "annullo" but they forgot to insert the quotes. If it was null, not a string, it could look like this, without quotes.
json = {example: null}
However, as annullo is an invalid word in javascript and is not as a string, it gives an error.
The correct thing to do is to correct the error in the source, transforming it to null, however, I believe that you can also use this regular expression. But do tests to ensure that there is no undue substitution elsewhere.
json.replace(/.+["']: ?annull(o|are)[\n,}]$/g, matched => {
return matched.replace(/annull(o|are)/, 'null')
})

JS parse object wrapped in a string using same quotes as object keys

Consider the following event payload data returned via WS:
{
id: "1",
foo: "{"bar":"baz"}"
}
The current output of JSON.stringify(event.foo):
"{\"bar\":\"baz\"}"
Also consider the backend have no real way to return the foo value formatted differently and I need to find a way to parse the string associated to this foo key in order to access it's value of bar.
The identified problem is the fact that the quotes used to wrap the whole supposed object are the sames used in the object itself, resulting in making JSON.parse() impossible.
I'm wondering if there is a "clean" way to achieve this.
So far, I tried:
using JSON.parse() which fails due to the format of the string raising Unexpected end of JSON input
trimming external quotes and converting inner ones to single then parsing, results in same error.
using new Object(...) based on the string (trimmed of external quotes)
replacing all quotes with single ones and wrapping it again in double ones to parse it.
Any input appreciated
The problem here is the backend should really be fixed, but some reason you can not do it. Next issue is you can "fix it" on the front end, but you are putting a band aid on the problem and it will fall off when the data that comes back is not what you expect. So the solutions will be error prone unless you know the data coming back will be a specific type.
With this said, you can fix the invalid JSON that you have in your simple example with a couple of regular expressions. Problem is, if your data contains characters such as } in the text, this is going to fail.
var response = `
{
id: "1",
foo: "{"bar":"baz"}",
goo: "{"gar":"gaz"}"
}
`
var reObj = /"(\{[^}]*})"/
while (response.match(reObj)) {
response = response.replace(reObj, '$1')
}
var reKey = /^\s+(\S+):/m
while (response.match(reKey)) {
response = response.replace(reKey,'"$1":')
}
var obj = JSON.parse(response)
console.log(obj)

Jquery: "Expected Comma but found <character>" error in Netbeans/Eclipse

Following is code which is giving above error, in netbeans as well as eclipse:
$(".bandListing").autocomplete({
source : [ ${bandnavn} ]
});
The error says:
1) Expected Comma but found {
source:[${bandnavn}]
2) Expected Comma but found ]
source:[${bandnavn}]
${bandnavn} is JSP object containing String of comma separated values which is put into array and assign to source. The code output is fine
Following is screenshot from Netbeans of same; could anyone guide me how to rectify the same?
If it could be fixed without do much changes, that will be helpful.
Store the value returned ${bandnavn} in a JavaScript variable, then use split() to create an array of string which can be supplied to autocomplete
var str = '${bandnavn}';
$(".bandListing").autocomplete({
source : str.split(',')
});

javascript object value to string conversion

I am getting the value of input using javascript using below code.
var name=document.getElementById("firstName").value;
Getting output like rk-chaitu.I want to split this output using reg expression.
Now my question is how to convert name object to String?
Regards,
Chaitu
name should already be a string. You can directly use name.split(separator).
EDIT: I see you have added information. Can you post more code? Perhaps the error comes from something else.
The value attribute should already be a String.

Fix JS object replacing/encoding of strings?

I have an object with a value that has spaces in it, and it gets replaced with an encoded string, like:
alldata["test"] will return "Long+name"
or something like
alldata["test"] will return "%BLong+name%B"
when it's set by using
alldata["test"] = "Long name" (or "[Long name]") via a series of code.
Am I missing something? I don't think using $.toEvalJSON is the right way to go because I haven't transformed the object into JSON. I'd rather not do a string.replace either because I'd have to capture every possible type of input that is encoded.
Thank you!
If your question is how to remove the encoding, you could always use
unescape(s)
See Escape and Unescape Functions
The issue is related to the fact that I failed to mention that the object was being assigned the string as a result of a .serialize() command. Hence a urldecode() will work perfectly.

Categories