Send JSON with unusual keys - javascript

I've object in js with keys-selectors:
{
"[data-index="0"]": {
// something
},
"> .class > .one": {
key: "very bad+ \"\' string"
}
}
How send this object via ajax without any changes in the keys and with correct values?
By correct values I mean that "very bad+ \"\' string" should be total escaped, but save all chars and signs to store in Database.
PS. I know that i can send objects via AJAX

JSON.stringify will transform your object into a JSON string. It can handle special characeters, don't worry.
var json = JSON.stringify(myObject);

When you modify your object a bit
var obj = {
"[data-index='0']": {
// something
},
"> .class > .one": {
key: "very bad+ \"\' string"
}
}
then a JSON.stringify(obj) works. The second pair of " after data-index= provokes an error.
-- edited syntax

Related

Access Value from JSON.parse

I'm having issues accessing values from json using json.parse. This is my JSON:
[
{
"store":[
{
"name":"Grand Theft Auto V"
},
{
"skuid":"UP1004-CUSA00419_00-GTAVDIGITALDOWNL-U001"
},
{
"releasedate":"2014-11-18T00:00:00Z"
} //...
I'm trying to get the name from the store array.
var cif = JSON.parse(response);
// Tried the following:
alert(cif["store"][0].name);
alert(cif.store[0].name);
alert(cif[0].store.name);
alert(cif["store"].name);
if(cif.store[0].name) $("#cif-title").html(cif.store[0].name);
How do I access this value?
This should work.
alert(cif[0]["store"][0]["name"]);
or
alert(cif[0].store[0].name);
Try console.log(cif[0].store[0].name)

Get comma separated string from array

I have the following JSON in JS.
{
"url":"http://example.com/main.aspx",
"report_template_id":"1",
"interval_secs":"86400",
"analysis_type":"lite",
"email":"rokumar#example.com",
"alerts":["num_domains", "med_load_time", "avg_load_time", "tot_req"]
}
I want the list of alerts to be removed and replaced with comma separated values as follows.
{
"url":"http://example.com/main.aspx",
"report_template_id":"1",
"interval_secs":"86400",
"analysis_type":"lite",
"email":"rokumar#example.com",
"alerts":"num_domains,med_load_time,avg_load_time,tot_req"
}
Just adding all the steps:-
1). Taking your JSON in a variable.
data = {"url":"http://example.com/main.aspx","report_template_id":"1","interval_secs":"86400","analysis_type":"lite","email":"rokumar#example.com","alerts":["num_domains","med_load_time","avg_load_time","tot_req"]};
2). Parse JSON data to object. Assuming the JSON is a string initially do a typeof(data) to be clear.
data = JSON.parse(data);
3) Change list of alerts to comma separated values
data.alerts = data.alerts.join(',');
4) Convert back to string
data = JSON.stringify(data)
So data will look like
{
"url": "http://example.com/main.aspx",
"report_template_id": "1",
"interval_secs": "86400",
"analysis_type": "lite",
"email": "rokumar#example.com",
"alerts": "num_domains,med_load_time,avg_load_time,tot_req"
}
Note:- If you will just say join() then also it will work, because default delimiter is , only, just to clarify I have given that.

How can i convert this AJAX json result (which has a key/value property) into a javascript array

Given the following json result, how can I convert the validationErrors key/value property into a nice array object in javascript so i can then do things like
errors[0].Key
or
errors[0].Value, etc...
NOTE: If it's easier to do the conversion with jQuery, then I'm happy to use that. Also, I'm getting the data via jQuery -> $.post...)
update:
Here's the actual json data so someone can answer this with JSFiddle please.
{
"aaaa": 0,
"bbbb": 0,
"cccc": null,
"validationErrors": {
"a1_7127763-1c7ac823-61d5-483f-a9ca-4947e9eb8145": "Invalid PropertyType. Please choose any property except Unknown.",
"a2_7127763-1c7ac823-61d5-483f-a9ca-4947e9eb8145": "A State is required. Eg. Victoria or New South Wales.",
"b1_5433417-18b5568a-d18e-45e2-9c63-30796995e2d3": "Invalid PropertyType. Please choose any property except Unknown.",
"b2_5433417-18b5568a-d18e-45e2-9c63-30796995e2d3": "A State is required. Eg. Victoria or New South Wales.",
"c1_6655305-297c57f9-a460-4101-be7d-70c6b9a565d5": "Invalid PropertyType. Please choose any property except Unknown.",
"c2_6655305-297c57f9-a460-4101-be7d-70c6b9a565d5": "A State is required. Eg. Victoria or New South Wales."
}
}
I would take all the keys of the object and then map them to an array.
var arrayOfErrors = Object.keys(objectOfErrors).map(function(errorKey) {
return objectOfErrors[errorKey];
});
You can use map to convert the object to an array:
var errors = jQuery.map(data.validationErrors, function (value, key) {
return {
"Key": key,
"Value": value
};
});
JSFiddle showing this approach: http://jsfiddle.net/WgaFb/1/
If you do not wish to use jQuery, here is a pure JavaScript method:
var errors = [];
for(var key in data.validationErrors) {
errors.push({
"Key": key,
"Value": data.validationErrors[key]
});
}
JSFiddle for this second approach: http://jsfiddle.net/4WXEF/1/

json web service Get value from dynamic parameter's name

please i have this output from my json web service:
{"format":"json",
"success":true,
"errors":[],
"result":
{"**206**":
{"player_name":"stagiaire",
"M":{
"6480":{"score":0,"answer":"cdgvbdbgd","category_name":"cdgvbdbgd"},
"6481":{"score":0,"answer":"cdgvbdbgd","category_name":"cdgvbdbgd"},
"6482":{"score":0,"answer":"cdgvbdbgd","category_name":"cdgvbdbgd"},
"6483":{"score":0,"answer":"cdgvbdbgd","category_name":"cdgvbdbgd"},
},
"O":{
..... },
}
}
}
What i want is to extract the value (which is now 206 but it can be another number).
I am asking for your help to achieve this goal.
Any help will be appreciated.
In case the resulting object contains only a single property with this number as its name, i.e.
result = {
206 : {
...
}
// no other properties here
}
then you can use something like:
var num = Object.keys(result).shift(); // "206"
Check the browser compatibility for Object.keys() method at MDN and use shim if needed.
If the object you look for always has a player name as value, try
for (var key in obj.result) if obj.result[key]["player_name") alert(key)
Or use jQuery
$.each(data.result,function(key,val) {
alert(key);
});

Dynamic Associative Array Creation in Javascript from JSON

It sounds a lot more complicated than it really is.
So in Perl, you can do something like this:
foreach my $var (#vars) {
$hash_table{$var->{'id'}} = $var->{'data'};
}
I have a JSON object and I want to do the same thing, but with a javascript associative array in jQuery.
I've tried the following:
hash_table = new Array();
$.each(data.results), function(name, result) {
hash_table[result.(name).extra_info.a] = result.(name).some_dataset;
});
Where data is a JSON object gotten from a $.getJSON call. It looks more or less like this (my JSON syntax may be a little off, sorry):
{
results:{
datasets_a:{
dataset_one:{
data:{
//stuff
}
extra_info:{
//stuff
}
}
dataset_two:{
...
}
...
}
datasets_b:{
...
}
}
}
But every time I do this, firebug throws the following error:
"XML filter is applied to non-xml data"
I think you can use the JSON response as an associative array. So you should be able to go directly in and use the JSON.
Assuming you received the above example:
$('result').innerHTML = data['results']['dataset_a']['dataset_two']['data'];
// Or the shorter form:
$('result').innerHTML = data.results.dataset_a.dataset_two.data;
Understand that I haven't tested this, but it's safer to use the square brackets with a variable than it is to use parenthesis plus the name with the dot accessor.
Your example is failing because of some convoluted logic I just caught.
$.each(data.results), function(name, result) {
hash_table[result.(name).extra_info.a] = result.(name).some_dataset;
});
Now, the foreach loop goes through the variable data.results to find the internal elements at a depth of 1. The item it finds is given to the lambda with the key of the item. AKA, the first result will be name = "datasets_a" item = object. Following me so far? Now you access the returned hash, the object in item, as though it has the child key in name ... "datasets_a". But wait, this is the object!
If all else fails... write your result JSON into a text field dynamically and ensure it is formatted properly.
Why would you want to change an array into another array ?-)
-- why not simply access the data, if you want to simplify or filter, you can traverse the arrays of the object directly !-)
This works. Just dump it into a script block to test.
d = {
'results':{
'datasets_a':{
'dataset_one':{
'data':{
'sample':'hello'
},
'extra_info':{
//stuff
}
},
'dataset_two':{
///
}
///
},
'datasets_b':{
///
}
}
}
alert(d.results.datasets_a.dataset_one.data.sample)
I hope this pasted in correctly. This editor doesn't like my line breaks in code.
d = {
'results':{
'datasets_a':{
'dataset_one':{
'data':{
'sample':'hello'
},
'extra_info':{
//stuff
}
},
'dataset_two':{
///
}
///
},
'datasets_b':{
///
}
}
};
alert(d.results.datasets_a.dataset_one.data.sample)

Categories

Resources