jquery data attribute not parsing json string - javascript

I am saving array of javascript objects in the html data attribute using JSON.stringify(). When I try to retrieve the data using jquery .data() function, I do not get deserialized array of javascript objects back, but gives me plain json string. I read, jquery .data() function deserializes Json string as quoted in documentation
When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string;
it must follow valid JSON syntax including quoted property names. If
the value isn't parseable as a JavaScript value, it is left as a
string
I think, mine is a valid json string, because, if I try $.parseJSON on that, it gives me back array of javascript objects.
Please help!

You don't need to stringify objects to store them using jQuery.data(). Just store the object like so:
var myobject = { "name":"john", "age":30};
jQuery('#dataholder').data('theobject',myobject);
console.log(jQuery('#dataholder').data('theobject'));
console.log(jQuery('#data_attribute_method').data('theobject'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dataholder"></div>
<div id="data_attribute_method" data-theobject='{ "name":"jim", "age":31}'></div>
jQuery will parse (as objects) hard coded data attributes at rendering time, but any data attribute you set as string afterwards, will be stored as text no matter if wrapped in curly braces or not.

Related

getting json object from cookie in proper json format in javascript

I am storing json object into cookies in browser window, but when I read cookie for the same json object I stored it returns me follwing json object:
"j%3A%7B%22request%22%3A%22login%22%2C%22provider%22%3A%22facebook%22%2C%22idd%22%3A1%2C%22auth_token%22%3A%22EAACQG9aNqPcBAFaWZCGG1UGsb1wqxqzaopZAFr1B3ZAR5tnNGQnLGcmuaHFjmvusPcBI9k3k5m6U89K3vZB4ruxadPHZA945lQtpc8fINoKQDQqZBXYhX0j0ZCupdxWc2VP5b86MvWtTGzBvWSxgEqHM74ZBcEhWZBF5PKc41VwOWAgZDZD%22%2C%22auth_name%22%3A%22Tushar%20Bochare%22%2C%22auth_email%22%3A%22mytusshar%40gmail.com%22%2C%22auth_id%22%3A%221414815471964057%22%2C%22cognito_id%22%3A%22us-east-1%3A2eb23ae9-bb78-40f7-b614-efe145dc1b7b%22%2C%22accessKey%22%3A%22ASIAJSIGNL2VUL3WVVZQ%22%2C%22secretKey%22%3A%22kKrFQzIl%2F4%2BqNTRa2XN4HMHjvzdaZo988QKf%2FLjO%22%2C%22status%22%3A1%2C%22name%22%3A%22fb%20tush%22%2C%22city%22%3A%22Akola%22%2C%22email%22%3A%22mytusshar%40gmail.com%22%2C%22message%22%3A%22LOGIN%20SUCCESS%22%7D"
my original JSON object that I stored is:
{"request":"login","provider":"facebook","idd":1,"auth_token":"yuiyuiiiyiyiiyissflkjljwqxqzaopZAFr1B3ZAR5tnNGQnLGcmuaHFjmvusPcBI9k3k5m6U89K3vZB4ruxadPHZA945lQtpc8fINoKQDQqZBXYhX0j0ZCupdxWc2VP5b86MvWtTGzBvWSxgEqHM74ZBcEhWZBF5PKc41VwOWAgZDZD","auth_name":"xyz smith","auth_email":"xyz#gmail.com","auth_id":"3123213171964057","cognito_id":"us-east-2:21wd2fh5-bb78-40a6-b614-efe145df2c4c","accessKey":"ASIAQFXSYL2VUL3WVVZQ","secretKey":"kKrKJzIl/4+qNTRa2YS4JBYjvzdaZo100QKf/LjO","status":1,"name":"fb xyz","city":"starcity","email":"xyz#gmail.com"}
It is replcaing all special characters like single quotes, braces, colon, quomma with its ascii code.
Is there any function in JS to directly retrieve json object from cookies?
You can use decodeURI(str)to decode your string. This function replace every %x characters.
Find doc here
You can use JSON.stringify() when storing "json object" & you can use
JSON.parse() to read json object from cookie.

accessing an object property that contains forward slashes

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

Parsing incoming JSON in JavaScript - what happens to the "extended parameters"?

I am attempting to parse the incoming JSON from XBMC (Eden Beta v3), an example string from XBMC is as follows:
{"jsonrpc":"2.0","method":"Player.OnPlay","params":{"data":{"item":{"type":"movie"},"player":{"playerid":1,"speed":1},"title":""},"sender":"xbmc"}}
I am using json2.js from https://github.com/douglascrockford/JSON-js/blob/master/json2.js to give me the JSON.parse and JSON.stringify functions in my application.
I am using the parse function in my code like this
var temp = JSON.parse(data);
Which is working fine for the first two properties, "jsonrpc" and "method"... so I can access those like this
temp.method
returns "Player.OnPlay"
temp.jsonrpc
returns "2.0"
However, if you look at the string sent by XBMC, it also contains what they refer to as "extended parameters" or "params", I cannot seem to track down what the JSON parser is doing with the rest of the message, or how I can access them in similar ways as the first two properties. If I try
params = temp.params
or any other way of accessing the params property, I get an Undefined error as there is no such property in the JSON object... I hope this is clear enough for someone to take a stab at helping me out. Will provide any extra info needed...
Thanks
The value of params in the JSON data is an object, so you have to access the sub-properties of that.
temp.jsonrpc
temp.method
temp.params["data"]["item"]["type"]
temp.params["data"]["player"]["playerid"]
temp.params["data"]["player"]["speed"]
temp.params["data"]["item"]["title"]
temp.params["sender"]

How could I add new property into a JSON string in JavaScript?

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.

GoogleAppEngine JSON object using javascript

I want to create a dictionary containing array and send it to GAE using jquery's ajax request.
something like- {'a':'text', 'b':'othertext','c':['texta','textb']} which I'm creating manually.
I am able to receive and process a and b using self.request.get on GAE but not the c.
Is there any other way to create JSON object in js? Please suggest whats wrong in this method.
You're not really sending JSON to the server. When you pass the object to jQuery.ajax (or the get/post wrappers), it will be serialized into GET or POST variables, not sent as JSON, so your object would be converted into something like this:
a=text&b=othertext&c[]=texta&c[]=textb
If you want to pass the entire object as JSON, you can convert it yourself by calling JSON.stringify (you will need to include json2.js for browsers that don't support the JSON object natively). Then you can wrap the JSON-encoded string in a map with whatever name you want:
jQuery.post(url, { json: JSON.stringify({a:'text', ...}) }, ...);
On the server side, you can access the JSON text by calling self.request.get("json"). Then you would have to parse the JSON string to extract the values. I don't know much about Python, but apparently you just need to import django.utils.simplejson and call simplejson.loads(json).
Presumably, GAE's self.request.get is not able to serialize a complex object like a string array into a GET request format (?a=text&b=othertext...).
One workaround, although perhaps not a very neat one, would be to serialize the value to JSON yourself, and pass that:
var jsonObj = {
'a':'text',
'b':'othertext',
'cJSON': JSON.stringify(['texta', 'textb'])
};
... and then of course you'd have to deserialize cJSON at the receiving end.
You're actually sending urlencoded request parameters, not JSON. JQuery is probably encoding the list as multiple values for the same parameter, which means you can access it using self.request.get_all, which will return a list - self.request.get will only return the first value.

Categories