I have created JSON by using the json_encode PHP function. The key of one of the items of the array contains a forward slash and when the JSON is parsed, the object looks like this when output in Chrome's console.
Object
contact/allow_anonymous: "0"
menulayout: "horizontal"
pages/max_pages: "10"
primarycolour: "329e95"
websitelogo: "text"
My problem is that I can't seem to be able to access the value of the properties that have a forward slash in them.
Any ideas? Since javascript allowed me to create the object I would assume there is a way to retrieve the values.
Just use myObject["key"] instead of myObject.key:
alert(myObject["contact/allow_anonymous"]);
Just replace the forward slash with ~1.
Instead of contact/allow_anonymous use contact~1allow_anonymous
Related
I am trying to return the value under the key 'str' in an Object but I am having trouble accessing the value.
This is what is returned in the console:
Currently I am using a map function to go over the array and just return the _str value like so:
let idx = currentArray.map(function(x) {
return x._id._str;
});
However it is still returning the value as an object. How can I get just the value of the _str key?
Here is the full array without specifying the id field. This is what is returned if you jsut return 'x' in the map function.
You've clarified that the screenshot is of x._id. So to access _str, you'd use x._id[0]._str: The _str property is in the object referenced by the 0 property (the first entry in the array x._id refers to).
Note that in general, _-prefixed properties are meant not to be accessed by code outside the code responsible for the objects in question. You don't seem to be responsible for them, so accessing those properties is likely to make your code rely on undocumented properties that may change in the next "dot" release of whatever lib you're using. It's just convention, but it's a very common convention.
If you right click on the property, most browser consoles offer the ability to copy property path.
Based on this SO post and the docs, it appears that you can probably use x._id.str.
If I understand correctly, you are receiving the str value but it is an object instead of the string literal. In other words, you are getting _str: "598..." instead of "598....". A possible solution would be to use the mongo javascript function to convert the str value to a string.
In your case, I think something like return x._id.str; may work as _id is a MongoID.ObjectID.
I've also linked the documentation below for reference.
https://docs.mongodb.com/manual/reference/method/ObjectId/
Here's a relevant SO answer as well: Convert ObjectID (Mongodb) to String in JavaScript
I think you should write x[_id]._str because _id is one of the array objects.
Either if you saying '-' takes as a subtract expression.
eg. Json = {'Me-m':123}
But have you idea why we need to use [] for access this hyphen variable.
Such like that Json['Me-m'].
Writting
Json.Me-m
will evaluate to
Json.Me - m
It will try to access Me property from Json object and subtract m variable, which probably will be undefined.
Because Me-m is not a valid property name to be used as property hence you are forced to use as Maps read this or check here for a valid propert name
That's because '-' has a meaning in javaScript, so if you write Json.Me-m JavaScript interprets: 'Substract the value of the variable m to the value of the attribute Me of the object ``Json`'.
In javascript, you can access any member of an object by name, using [], and inside a string, javascript is not going to try to evaluate anything, so when you write Json[Me-m], it's interpreted as: 'Retrieve the value of the member named Me-m of the object Json'
The reason is simple: in Javascript each object it's an indexed key/value dictionary, accessing to the variable with the "." it's a shortcut, and obviously the fact of the "dictionary object" it's a performance issue, but despite of this matter, javascript it's really fast in comparison with other scripting language.
Answering your question, by desing an index can be a string containing the "-" char, but not a property... so if you have a property with that char, it won't be accessible with the "." notation.
Because you are passing a special character in key part of obj and for accessing that value of obj we need to use [].
eg. json['Me-m']
My response object has a field called "50", so right now I'm trying to access and save that data doing something like this:
var thing = $scope.data.array[0].50;
However I'm getting an error on the console when I simply reload the page with the function not even running. When I get rid of the 50, everything is fine. There is indeed a field called "50" inside the $scope.data.array[0] and I do not have access to change the response. Is there something wrong with this because the field is called "50" and maybe JS is interrupting that as a number instead??
Also when I changed "50" to something random like "af", then I get no errors on refresh.
this doesn't work
var thing = $scope.data.array[0].50;
this works
var thing = $scope.data.array[0].af;
The following should work if your first element of the array has a property called "50".
var thing = $scope.data.array[0]["50"];
Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
Syntax
object.property
object["property"]
JavaScript objects are also associative arrays (hashes). Using these you can associate a key string with a value string as shown in the example above.
The reason as to why you don't get an error when accessing $scope.data.array[0].af; is because "af" is valid identifier for a property. Dot notation only works with property names that are valid identifiers. An identifier must start with a letter, $, _ or unicode escape sequence.
For all other property names, you must use bracket notation.
By JSON text, I mean the return value of JSON.stringify. I know how to do this with JSON object, but I couldn't figure out how to do this with JSON text (add new attribute/element, say "sn":"1" to JSON text, but its structure is kept and I don't need to stringify it again), can anyone help me?
Thanks!
I don't know why you'd want to do this - why not just add the property before you stringify it?
But if you must, given a string that contains JSON:
var myJSON = '{"prop1":"val1","prop2":"val2"}';
You can easily add a property to the beginning by doing this:
myJSON = '{' + '"sn":"1",' + myJSON.substr(1);
Or add it to the end:
myJSON = myJSON.replace(/}$/, ',"sn":"1"' + '}');
Or use whatever other combination of String manipulation functions takes your fancy...
If you want to add the new property in a specific place within the string, say inside a nested object or array or something, well, again some kind of regex or combination of .indexOf() and .substr() or something could do it, but really I think it's nuts to approach it this way.
Obviously the above code can be wrapped up in a function, and '"sn":"1"' can be replaced with a parameter or variable name or whatever - but why?
Note also that I've assumed above that there will be at least one existing property and inserted a comma accordingly- up to you to make that smarter if you want to allow for empty objects.
P.S. There aren't "JSON strings" and "JSON objects": all JSON is a string. In JavaScript one way of creating objects is with the object literal syntax that inspired JSON, but there's no such thing as a JSON object.
It makes no sense to do it the way you're suggesting... just turn it back into an Object, add your field and stringify it again! Or am I missing something?
You're going to have to parse it somehow. The most straightforward way is probably un-stringifying it to object/array/literal data. But if you don't want to do that, you could either use regular expressions, or methods of the String object like substr to manipulate the string directly.
Hello i have an url in my jsp and i want to pass an array of string in this url to recover in my ActionForm
If you are dealing with something simple like a list of numeric ids, i would just run through the check boxes, create a comma separated list, and assign it to a query string parameter. On the other side i would split the string.
If the values are more complex you have to consider escape characters. Also if you are dealing with a long list, the url is not the best way to pass this data.
You can use 'standard' html way of passing arrays of data: http://mywebsite/mypage?myarray=value1&myarray=value2&myarray=value3. Then you can fetch all values of parameter myarray from request object (if framework doesn't provide more elegant ways of handling arrays).
But seeing your comment, I would recommend to leave JavaScript and just declare a form for it.
If you need a link (not button), you can always submit form from it. Something like ...
Try Json encode
http://code.google.com/p/json-simple/
Check this