how to convert string from div attribute to object - javascript

i try convert a string to object. i use :
var ec = $(".selector").attr('build'); // this return {abc:'one', bcm:'two', etc...}
var et = ec.abc // this return me undefined
i try this way
var et = new Object(ec);
var t = et.abc // this return undefined
How can convert this ??

If that attribute contains a string that just happens to be in the format of a Json object, you have to parse the string first to be able to access elements of it in a way that you would working with Json:
var ec = $(".selector").attr('build');
var myObject = JSON.parse(ec);
var et = myObject.abc;
Of course you might want to add validation around that string to make sure it's always going to be in that form, otherwise you could run into issues by making those sorts of assumptions.
Also, is there a reason you are storing a Json string in an HTML attribute?

Use $.parse() method
var et= $.parse($(".selector").attr('build'));
var t = et.abc

If this
var ec = $(".selector").attr('build');
returns this
// this return {abc:'one', bcm:'two', etc...}
then you already have an object.

You need to parse the string using a JSON parser. You can't just pass the string to the Object constructor.

Instead of using attr(), try using the data() method, which will allow you to store object, not just strings.
When you store your object, use the following syntax:
var d = {abc:'one', bcm:'two'};
$(".selector").data('build', d);
Then, when you need to retrieve your object, use:
var d = $(".selector").data('build');
//access properties
var x = d.abc;
Otherwise, if you use attr(), you will need to parse the result into an object, which you can use parseJSON for.

Related

Get jqGrid ajax Nested Array of Json string in C# by Newtonsoft Json

I'm trying to parse Json string and collect array values present inside it.
{"_search":true,"nd":1492064211841,"rows":30,"page":1,"sidx":"","sord":"asc","filters":"{\"groupOp\":\"OR\",\"rules\":[{\"field\":\"Emp_ID\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Name\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Designation\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"City\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"State\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Country\",\"op\":\"cn\",\"data\":\"ASAS\"}]}"}
PS: Above string is coming from jqGrid Ajax to the WebMethod in C#.
I'm not getting success on getting filters->rules[0]->data
What I've tried :
dynamic jObj = JObject.Parse(postData);
var data = jObj.filters.rules[0].data;
getting error: 'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'rules'.
dynamic jObj = JObject.Parse(postData);
var filters = jObj.filters; //Sucess: getting filters here
var rules1 = filters["rules"]; //Error: 'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'rules'.
var rules2 = filters.rules; //Error: 'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'rules'.
How to get value inside filters->rules AND filters->rules[0]->data ?
You must parse the internal object like this :
var obj = "{\"_search\":true,\"nd\":1492064211841,\"rows\":30,\"page\":1,\"sidx\":\"\",\"sord\":\"asc\",\"filters\":\"{\\\"groupOp\\\":\\\"OR\\\",\\\"rules\\\":[{\\\"field\\\":\\\"Emp_ID\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"Name\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"Designation\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"City\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"State\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"},{\\\"field\\\":\\\"Country\\\",\\\"op\\\":\\\"cn\\\",\\\"data\\\":\\\"ASAS\\\"}]}\"}";
dynamic jObj = JObject.Parse(obj);
var data = JObject.Parse(jObj.filters.Value);
var test = data.rules;
Console.WriteLine(data);
Console.ReadLine();
I don't have the knowledge about C# but I have tried into it on JavaScript
In your json, in filters field not is'nt proper json it is string
I have do this on javascript might it will help's you
var a = {"_search":true,"nd":1492064211841,"rows":30,"page":1,"sidx":"","sord":"asc","filters":"{\"groupOp\":\"OR\",\"rules\":[{\"field\":\"Emp_ID\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Name\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Designation\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"City\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"State\",\"op\":\"cn\",\"data\":\"ASAS\"},{\"field\":\"Country\",\"op\":\"cn\",\"data\":\"ASAS\"}]}"}
console.log(a.filters)
it is returns
"{"groupOp":"OR","rules":[{"field":"Emp_ID","op":"cn","data":"ASAS"},{"field":"Name","op":"cn","data":"ASAS"},{"field":"Designation","op":"cn","data":"ASAS"}
and it is string now i'm again parse into it on JSON
b = JSON.parse(a.filters)
console.log(b.rules)
now it returns rules objects

How to get item from JSON object when there is only one item?

I have the following JSON:
var x = [{"email":"info#test.nl"}]
How do I get the email in javascript? x.email doesn't work for me.
Bart
You need to reference to element of the array, then access the property.
var x = [{"email":"info#test.nl"}]
console.log(x[0].email)
Since the object is inside of an array, you must access the correct array element first, so use: x[0].email
if you want to read the JSON inside an array, use x[0].email.
You need to parse the JSON first:
var arr = JSON.parse(x);
var entry = arr[0].email;

access javascript object in servlet [duplicate]

I am creating and sending a JSON Object with jQuery, but I cannot figure out how to parse it properly in my Ajax servlet using the org.json.simple library.
My jQuery code is as follows :
var JSONRooms = {"rooms":[]};
$('div#rooms span.group-item').each(function(index) {
var $substr = $(this).text().split('(');
var $name = $substr[0];
var $capacity = $substr[1].split(')')[0];
JSONRooms.rooms.push({"name":$name,"capacity":$capacity});
});
$.ajax({
type: "POST",
url: "ParseSecondWizardAsync",
data: JSONRooms,
success: function() {
alert("entered success function");
window.location = "ctt-wizard-3.jsp";
}
});
In the servlet, when I use request.getParameterNames() and print it out to my console I get as parameter names rooms[0][key] etcetera, but I cannot parse the JSON Array rooms in any way. I have tried parsing the object returned by request.getParameter("rooms") or the .getParameterValues("rooms") variant, but they both return a null value.
Is there something wrong with the way I'm formatting the JSON data in jQuery or is there a way to parse the JSON in the servlet that I'm missing?
Ask for more code, even though the servlet is still pretty much empty since I cannot figure out how to parse the data.
The data argument of $.ajax() takes a JS object representing the request parameter map. So any JS object which you feed to it will be converted to request parameters. Since you're passing the JS object plain vanilla to it, it's treated as a request parameter map. You need to access the individual parameters by exactly their request parameter name representation instead.
String name1 = request.getParameter("rooms[0][name]");
String capacity1 = request.getParameter("rooms[0][capacity]");
String name2 = request.getParameter("rooms[1][name]");
String capacity2 = request.getParameter("rooms[1][capacity]");
// ...
You can find them all by HttpServletRequest#getParameterMap() method:
Map<String, String[]> params = request.getParameterMap();
// ...
You can even dynamically collect all params as follows:
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String name = request.getParameter("rooms[" + i + "][name]");
if (name == null) break;
String capacity = request.getParameter("rooms[" + i + "][capacity]");
// ...
}
If your intent is to pass it as a real JSON object so that you can use a JSON parser to break it further down into properties, then you have to convert it to a String before sending using JS/jQuery and specify the data argument as follows:
data: { "rooms": roomsAsString }
This way it's available as a JSON string by request.getParameter("rooms") which you can in turn parse using an arbitrary JSON API.
Unrelated to the concrete problem, don't use $ variable prefix in jQuery for non-jQuery objects. This makes your code more confusing to JS/jQuery experts. Use it only for real jQuery objects, not for plain vanilla strings or primitives.
var $foo = "foo"; // Don't do that. Use var foo instead.
var $foo = $("someselector"); // Okay.

Javascript: How to convert JSON dot string into object reference

I have a string: items[0].name that I want to apply to a JSON object: {"items":[{"name":"test"}]} which is contained in the variable test. I want to apply that string to the object in order to search it (test.items[0].name). I can only think of one way to do this: parse the square brackets and dots using my own function. Is there another way I can do this? Perhaps using eval? (Even though I'd LOVE to avoid that...)
For clarity:
I have a JSON object, what is inside of it is really irrelevant. I need to be able to query the object like so: theobject.items[0], this is normal behaviour of a JSON object obviously. The issue is, that query string (ie. items[0]) is unknown - call it user input if you like - it is literally a string (var thisIsAString = "items[0]"). So, I need a way to append that query string to theobject in order for it to return the value at theobject.items[0]
function locate(obj, path) {
path = path.split('.');
var arrayPattern = /(.+)\[(\d+)\]/;
for (var i = 0; i < path.length; i++) {
var match = arrayPattern.exec(path[i]);
if (match) {
obj = obj[match[1]][parseInt(match[2])];
} else {
obj = obj[path[i]];
}
}
return obj;
}
var name = locate(test, 'items[0].name');
...JSON doesn't have objects, it's just a string.
If you're dealing with an object (ie: you can reference it using dot/bracket notation) then it's just a JavaScript object/array...
So depending on what the deal is, if you're dealing with a 100% string:
'{"name":"string","array":[0,1,2]}'
Then you need to send it through JSON.parse;
var json_string = '{"name":"string","array":[0,1,2]}',
js_obj = JSON.parse(json_string);
js_obj.name; // "string"
js_obj.array; // [0,1,2]
js_obj.array[1]; // 1
If it's not a string, and is indeed an object/array, with other objects/arrays inside, then you just need to go:
myObj.items[0].name = items[0].name;
If it IS a string, then .parse it, and use the parsed object to do exactly what I just did.
If it needs to be a string again, to send to the server, then use JSON.stringify like:
var json_string = JSON.stringify(js_obj);
Now you've got your modified JSON string back.
If you need to support GhettoIE (IE < 8), then download json2.js from Douglas Crockford, and add that script on the page conditionally, if you can't find window.JSON.

New to JSON, what can I do with this json response

A website returns the following JSON response, how would I consume it (in javascript)?
[{"ID1":9996,"ID2":22}]
Is JSON simply returning an array?
We use:
function evalResponse(response) {
var xyz123 = null;
eval("xyz123 = " + response);
return xyz123;
}
An alternative method is to simply use:
var myObj = eval(response);
Basically, you have to call eval() on the response to create a javascript object. This is because the response itself is just a string when you get it back from your AJAX call. After you eval it, you have an object that you can manipulate.
function myCallback(response) {
var myObj = evalResponse(response);
alert(myObj.ID1);
}
You could use a javascript library to handle this for you. Or, you could try to parse the string yourself. eval() has it's own problems, but it works.
If you use http://www.JSON.org/json2.js you can use it's method JSON.parse to retrieve the json string as an object (without the use of eval (which is considered evil)), so in this case you would use:
var nwObj = JSON.parse('[{"ID1":9996,"ID2":22}]');
alert(nwObj.ID1); //=> 9996
It looks like an array with a single object holding two properties. I'd much prefer to see the same data structured like this:
{"ID":[9996,22]}
Then you have a single object holding an array with two elements, which seems to be a better fit for the data presented. Then using Endangered's evalResponse() code you could use it like this:
var responseObj = evalResponse(response);
// responseObj.ID[0] would be 9996, responseObj.ID[1] would be 22
I think the other answers might not answer your question, maybe you're looking for a way to use that "array of 1 object". Maybe this can help:
var arr = [{"ID1":9996,"ID2":22}];
var obj = arr[0];
var id1 = obj.ID1;
var id2 = obj.ID2;
Here's how you get to your data:
<script type="text/javascript" >
var something = [{"ID1":9996,"ID2":22}]
alert(something[0].ID1)
</script>
The JSON you posted represents an array containing one object, which has attributes ID1 and ID2 (initialized to the respective values after the colon).
To convert the string to a javascript object, pass it to eval, like this:
var obj = eval('[{"ID1":9996,"ID2":22}]');
However, this method will fail if you only have a single object instead of an array, so it is safer to wrap it in parenthesis:
var obj = eval('(' + jsonResponse + ')');

Categories

Resources