I have a function which only works if JSON object is passed to it. If I pass a string to it, with same format as JSON, it doesnt work. So I want to make that function think that the string passed to it is a JSON. The string is indeed in the JSON format.
I also tried the following. I inputted the string through Ajax , with "handle as" parameter as "JSON", and then when I passed the result to the function it works.
So I deduced the problem is not with the string. How do i convert this string to JSON? If i get same string through ajax request and then passing it to function works, whereas directly passing it doesnt work.
Screenshot of console log:
Advance Thanks
JavaScript is a dynamically typed language, so you can't really specify types of function arguments up front. If you want that, look into TypeScript.
JSON is nothing but a String, not a standalone type in JavaScript. To convert a JavaScript object to the equivalent JSON string representation use:
const myJSON = JSON.stringify ({ a: 'b' })
To get a JavaScript object back from a JSON string use:
JSON.parse (myJSON)
When going over the network, libraries can automatically return serialized objects if you specify the type as JSON. You haven't pasted any code, so I'm guessing that you haven't specified application/json as the Content-Type in your network request. Since you've tagged your question jQuery, take a look at [$.getJSON][2], this should do what you want.
Use JSON.parse
function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Example:
function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
str = '{"a":1, "b":2}';
console.log(isJson(str)); // true
str1 = '{["a":1, "b":2]}';
console.log(isJson(str1)); // false
Related
I have the following C# method:
[HttpPost]
public JsonResult GetDateBasedRegex(string date)
{
string[] arr = CommonMethods.GetDateBasedRegex(date);
JsonResult retVal = Json(JsonConvert.SerializeObject(retVal));
return retVal;
}
arr contains the following:
And retVal.Data contains this value:
That C# method is invoked by this JS:
var date = $('#myDateField').val();
AjaxRequest(date, 'html', 'post', '/Common/GetDateBasedRegex', 'application/json;', function (response)
{
var result = JSON.parse(response);
}
);
I've set a breakpoint and added a watch for both response and result:
response is slightly longer because it escapes the quotes but otherwise they're the same value.
Both variables are a single string. How can I parse this value into an array? I looked at a variety of "suggested questions" by SO when typing this question,
the most relevant one seems to be this: Javascript how to parse JSON array but I'm already doing what the selected answer suggests.
I tried making a JS fiddle: http://jsfiddle.net/zc2o6v52/ but due to the quotes added by the debugger I had to tweak the values slightly in order to get it to work. If I use the variable csharpJsonSerializedString or result the loop works but when I use response I get an "Uncaught SyntaxError: Unexpected string" error in my console.
What am I doing wrong? How do you parse an array from a JSON string?
EDIT
C# retval's value:
"[\"^[0-9]{9}[A-Z0-9]{0,3}$\",\"^[A-Z]{1,3}([0-9]{6}|[0-9]{9})$\"]"
JS response's value:
""[\"^[0-9]{9}[A-Z0-9]{0,3}$\",\"^[A-Z]{1,3}([0-9]{6}|[0-9]{9})$\"]""
JS result's value:
"["^[0-9]{9}[A-Z0-9]{0,3}$","^[A-Z]{1,3}([0-9]{6}|[0-9]{9})$"]"
Grabbed all of these by right click -> Copy value, so they include the 'wrapping' set of quotes to make it a string.
The C# looks like it's formed right for how one would define a JS array. It seems like response is wrapped with an extra set of quotes though?
I also tried changing my JS to define var result = ['','']; outside of the ajax call, then to update its value with JSON.parse() but it still remains a single string afterwards.
Assuming this is the exact value your API returns on the POST request
"[\"^[0-9]{9}[A-Z0-9]{0,3}$\",\"^[A-Z]{1,3}([0-9]{6}|[0-9]{9})$\"]"
This is no json, so JSON.parse can't work. Your JSON should look like this:
[
"^[0-9]{9}[A-Z0-9]{0,3}$",
"^[A-Z]{1,3}([0-9]{6}|[0-9]{9})$"
]
The best way would be to fix the backend to return the right value (this might point you in the right direction). Otherwise, you need to get rid of the quotation marks at the beginning and end which are added to your result variable:
var result = "\"[\"^[0-9]{9}[A-Z0-9]{0,3}$\",\"^[A-Z]{1,3}([0-9]{6}|[0-9]{9})$\"]\"";
result = result.substring(1, result.length-1);
var jsonData = JSON.parse(result);
for (var i = 0; i < jsonData.length; i++) {
console.log(jsonData[i]);
}
If that doesn't work, check how your response data in the ajax function differs from the valid json mentioned above.
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.
var saurabhjson= JSON.stringify(data)
above returns this json
saurabhjson {"recordId":5555,"Key":"5656"}
if print the first array in console it get undefined value
console.log("saurabhjson[0].recordId",saurabhjson[0].recordId);
i want to do some check like this
if(saurabhjson[0].recordId == 5555) {
$('#div_ajaxResponse2').text("another success");
}
As the method suggests JSON.stringify(data). It converts a js object to a jsonstring now if you want a key out of this string it can't be done before parsing it to json.
So i don't get it why do you need to stringify it.
And another thing is you have a js object not an array of objects. so you need to use this on data itself:
console.log("data.recordId",data.recordId);
You are probably mixing a few things there.
When you do var saurabhjson= JSON.stringify(data), that saurabhjson variable is a string, not an object, so you can't access its elements like you are trying to do.
Try accessing data directly instead, without using JSON.stringify():
console.log("data.recordId",data.recordId);
I have following json string. I need only 'locked' item and need to pass to a jquery function.I used json encode from php to get the string.
{"ignored":[],"status":{"message":"success","code":200},"locked":[8089033,8092415]}
My jquery function is as follows
$.map(locked, function (id) {
$("#grid-table tr#" + id)
.find("input[type=checkbox]")
.after($("<img src='http://www.placehold.it/20x10/ff0000'>"));
});
});
I am not getting an idea how to get only locked= [8089033,8092415]; to my jquery function
First make sure you have a valid Json string using a validator like this jsonlint
To get only locked you can parse the Json like this
var obj = jQuery.parseJSON( '{"ignored":[],"status":{"message":"success","code":200},"locked":[8089033,8092415]}' );
Then you can get the Locked object like this
obj.locked
I have a single level JSON to search through for the presence of a given value. Is there is a compact method provided in ecma5 for the same ?
Parse the JSON string with JSON.parse to get a JavaScript Object.
Use in operator to check the member existence
var jsObj = JSON.parse('{"p": 5}');
console.log(jsObj);
if ("p" in jsObj) {
console.log("`p` exists");
}
Output
{ p: 5 }
`p` exists
Since it sounds like you're looking for a specific value in an unknown key, assuming there that you already parsed your JSON, you'll need something more like:
function valueExists(jsObj, value){
for (var key in jsObj){
if (jsObj[key] == value) return true;
}
return false;
}
Parse the JSON string with JSON.parse to get a JavaScript Object,
and do
Simplest check,
if(jsonObj['key']) {
}
Working fiddle