Converting json array to query string gives null - javascript

What I am trying to achieve is to send a json object as a querystring to an API.
The json object I have is:
{
"Name":"Dlsajdsa",
"ImageUrls":["/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"]
}
I would like to convert this to something like ?Name=&ImageUrls=
However, when using $.param(json) I get the following:
?Name=Dlsajdsa&ImageUrls%5B%5D=%2FImages%2FFacility%2F8353%2F85e26a18-4366-4412-b37a-72d94f2ccda5.jpg
This result, on the API point of view, that the ImageUrls array is null.
What am I missing here?

you can try $.param(json,true)

Based on the documentation of jQuery.param, I'd say this is the piece of code you want to use:
var json = {
"Name":"Dlsajdsa",
"ImageUrls":["/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"]
};
var recursiveDecoded = decodeURIComponent($.param(json));
// "Name=Dlsajdsa&ImageUrls[]=/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"

The query parameter is called ImageUrls%5B%5D, that means ImageUrls[], not ImageUrls as you expect.

Related

Json associative array accessing in jQuery

I am getting response in below format for every product and in a single call there can be many products. I am trying to access this data via jQuery but I'm not able to access it.
Productdata['someid'] = { "Product Json data"}
I am using below syntax in jQuery but not getting the data. Please suggest.
alert(Productdata['someid']);
Its not going as JSON format .
JSON is a key : value pair format ;
so your Productdata should be in below format:
Productdata = { 'someid' : "Product Json data"}
A Json like this
var data={"name":"somebody"};
To call
return data.name
Or
return data["name"]
The problem here is that JavaScript does not support associative arrays (scroll down to "Associative arrays, no way!"). It has some internal workarounds which make it appear as if it does, but really all it does is just adding the keys as properties.
So you would most likely be able to access it using Productdata.someid = ....
EDIT:
So assuming you have the following JSON string: {"id":"123"} (which is valid JSON), you can use it like this:
var jsonString = '{"id":"123"}';
var parsedJSON = $.parseJSON(jsonString);
var productID = "product_" + parsedJSON.id;
Does this help?
Some useful links: JSON format checker to make sure the JSON is valid.
Unfortunately I wasn't allowed to add more than 2 links, so the jQuery parseJSON function link is still in the comment below.

Issue mapping Json string with ko.mapping

On the server side I have a Asp.Net Web application, a WebMethod returns a Json string serialized just like this one:
Object { d= "[{"Id":"1","Name":"COMERCIAL BANK"},
{"Id":"2","Name":"AZTEC BANK"},
{"Id":"3","Name":"EL SALVADOR BANK"}]" }
When I try mapping that result using var mappedBanks = ko.mapping.fromJSON(data.d), and then use console.log(mappedBanks) all I get printed is c() and is like that mappedBanks, that should be an array, has no elements because I can iterate on it and when I try to print the first element, the console says undefined. Is there a problem with the Json? or I´m not mapping it right.
ko.mapping.toJSON requires first argument to be an object, not an array. Your option is to make your JSON-encoded array to be property value.
var mappedBanks = ko.mapping.fromJS({ items: JSON.parse(data.d) });
console.log(mappedBanks.items);

Javascript: Parse JSON output result

How can i retrieve the values from such JSON response with javascript, I tried normal JSON parsing seem doesn't work
[["102",true,{"username":"someone"}]]
Tried such codes below:
url: "http://somewebsite.com/api.php?v=json&i=[[102]]",
onComplete: function (response) {
var data = response.json[0];
console.log("User: " + data.username); // doesnt work
var str = '[["102",true,{"username":"someone"}]]';
var data = JSON.parse(str);
console.log("User: " + data[0][2].username);
Surround someone with double quotes
Traverse the array-of-array before attempting to acces the username property
If you are using AJAX to obtain the data, #Alex Puchkov's answer says it best.
So the problem with this is that it looks like an array in an array. So to access an element you would do something like this.
console.log(obj[0][0]);
should print 102
Lets say you created the object like so:
var obj = [["102",true,{"username":someone}]];
this is how you would access each element:
obj[0][0] is 102
obj[0][1] is true
and obj[0][2]["username"] is whatever someone is defined as
From other peoples answers it seems like some of the problem you may be having is parsing a JSON string. The standard way to do that is use JSON.parse, keep in mind this is only needed if the data is a string. This is how it should be done.
var obj = JSON.parse(" [ [ "102", true, { "username" : someone } ] ] ")
It depends on where you are getting JSON from:
If you use jQuery
then jQuery will parse JSON itself and send you a JavaScript variable to callback function. Make sure you provide correct dataType in $.ajax call or use helper method like $.getJSON()
If you getting JSON data via plain AJAX
then you can do:
var jsonVar = JSON.parse(xhReq.responseText);

How to store a json array with .NET?

I Have a json array like
[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]
How can i pass(to the backend) and store(in db) that javascript object with asp.net??
EDIT:
OK to make it clearer, in some page, i got a javascript object
var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}];
, how can i pass it to some handler (like using
`$.post({url:"handler.ashx", data:array})
??), then in backend how can i save it into database or load this array later??
OR:
I'll appreciate it if u teach me how to convert
var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}];
into:
var arraystring = '[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]';
EDIT2:
Now i use the string-solution (traversal the array and add some '"' ':' ',' '{}' manually) as i mentioned just above, is there any potential problems??
You have several options when dealing with JSON on .NET
You can simply keep the array as is in the DB and retrieve it as is and use it
You can parse it into an Object using JSON.NET Library
for example on the 2nd case you simple use the JSON.NET method:
Newtonsoft.Json.Converters.KeyValuePairConverter
Or be fancy and use a Custom Deserialize as it's really easy to pass to and from JSON.
Let's imagine that you are posting something like this:
$.post("myForm.aspx",
[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}],
function() {
// all done.
});
This will be converted to A,B,C when requesting the data using Request.Form["name"] or simply Request["name"] so you should change all the naming convention first and then you can simple use Request["nameA"], Request["nameB"], etc...
You would store it just like any other string you wanted to store in the database. If you want to re-instantiate it later in JavaScript you use the eval() function on the string to convert it back into an object.
The best way to do this is to de-serialize the json into object and save it to db as records.
Check JSON.NET library http://json.codeplex.com/
public class MyObj
{
public string name{get;set;}
public string value{get;set;}
}
void Main()
{
string json ="[{\"name\":\"A\",\"value\":\"A\"},{\"name\":\"B\",\"value\":\"B\"},{\"name\":\"C\",\"value\":\"C\"}]";
IList<MyObj> arr = JsonConvert.DeserializeObject<IList<MyObj>>(json);
foreach(MyObj o in arr)
{
//add each object to db...
Console.WriteLine(o.name+":"+o.value);
}
}
Ok it turns out that using JSON.parse and JSON.stringify is a not-bad solution.

How to retrieve value from object in JavaScript

Hi I am using a Java script variable
var parameter = $(this).find('#[id$=hfUrl]').val();
This value return to parameter now
"{'objType':'100','objID':'226','prevVoting':'" // THIS VALUE RETURN BY
$(this).find('[$id=hfurl]').val();
I want to store objType value in new:
var OBJECTTYPE = //WHAT SHOULD I WRITE so OBJECTTYPE contain 400
I am trying
OBJECTTYPE = parameter.objType; // but it's not working...
What should I do?
Try using parameter['objType'].
Just a note: your code snippet doesn't look right, but I guess you just posted it wrong.
Ok, not sure if I am correct but lets see:
You say you are storing {'objType':'100','objID':'226','prevVoting':' as string in a hidden field. The string is not a correct JSON string. It should look like this:
{"objType":100,"objID":226,"prevVoting":""}
You have to use double-quotes for strings inside a JSON object. For more information, see http://json.org/
Now, I think with $(this).find('[$id=hfurl]'); you want to retrieve that value. It looks like you are trying to find an element with ID hfurl,but $id is not a valid HTML attribute. This seems like very wrong jQuery to me. Try this instead:
var parameter = $('#hfurl').val();
parameter will contain a JSON string, so you have to parse it before you can access the values:
parameter = $.parseJSON(parameter);
Then you should be able to access the data with parameter.objType.
Update:
I would not store "broken" JSON in the field. Store the string similar to the one I shoed above and if you want to add values you can do it after parsing like so:
parameter.vote = vote;
parameter.myvote = vote;
It is less error prone.

Categories

Resources