I am running a Javascript function on the latest version of Mozilla which receives a string which I want to convert to a JSON object. The conversion seems to be failing.
The string is being generated on the server side in a Java function:
result = "[{ \"userID\": 1 \"firstName\":\"John\" \"lastName\":\"Sheridan\" }{ \"userID\": 2 \"firstName\":\"Michael\" \"lastName\":\"Geribaldi\" }]";
(note that I am attempting to return an array of values for a list).
The code on the client side is the ajax callback shown below:
var successFunc = function(data, textStatus, jqXHR)
{
alert("Data: "+data);
var obj = $.parseJSON(data);
alert("Object: "+obj);
}
Apparently, the data is coming back to the callback and is being displayed in its string form, but the JSON parser is failing because the second alert is failing to appear. I am sure something is wrong with my string but am having trouble figuring out what. The debugger is not telling me anything, I am just seeing a silent failure.
I have also attempted this using the JSON.parser() function. I am seeing the same thing. I am making a mistake somewhere. Can someone tell me where?
Your json is not valid, you are missing comma
In order to parse your json should be like this
[
{ "userID": 1, "firstName":"John", "lastName":"Sheridan" },
{ "userID": 2, "firstName":"Michael", "lastName":"Geribaldi" }
]
JSON is a format where data is in key:value pairs separeted by , and key and value are enclosed in double quotes, where objects are enclosed in {} braces and array is enclosed in [] hope you have got the your mistake that where your json is lacking.
"[{
\"userID\": 1 ,
\"firstName\":\"John\",
\"lastName\":\"Sheridan\",
},
{
\"userID\": 2 ,
\"firstName\":\"Michael\",
\"lastName\":\"Geribaldi\" }]"
Related
In my JavaScript file,
The declaring and json parse for the ajax response text is like this:
var subcats = JSON.parse(this.responseText);
The supposed responseText for the parsing is like this:
{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"}{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}
and it gives me this error:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 64 of the JSON data
what's the syntax error? help
Your JSON have multiple elements and therefore should be wrap in an Array/List like this
[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"}{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]
Hope it helps
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. So you can use it like this if you have a single item:
JSON.parse('{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager"}');
but in your case you have multiple items that should be wrapped inside brackets [] and separated by commas or there is SyntaxError:
JSON.parse('[{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager" }, { "presubcatId": "2", "precatId": "1", "presubcatName": "Marketing Manager"}]');
var string = '[{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager" }, { "presubcatId": "2", "precatId": "1", "presubcatName": "Marketing Manager"}]';
var json = JSON.parse(string);
console.log(json);
Your JSON is invalid. You need change it like this:
[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]
your JSON data is invalid so that you are having problem,
var temp=[];
temp=[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]
console.log(JSON.stringify(temp))
Your JSON have multiple elements. So it must be treated like Array. See below image.
Below is valid JSON structure.
[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]
Your json object is not a valid json. You can check it on this site. It helps me a lot when I need to format or validate a Json object.
https://jsonlint.com/
Here is your json object formatted and it says what you are missing.
I'm working on a D3 component when a question springs to mind. As I'm experementing with different arrays, I'm wondering why they need different treatment of data, when they all contain the same.
First case: I have a 'hardcoded' array, which looks like the following:
var tmp = [
{
"Weight": 0.0,
"Speed": 59.9,
"Depth": 362.24000,
"Time": "2014-04-09T10:01:23",
"Id": 0
}, {
"Weight": 10.0,
"Speed": 59.9,
"Depth": 394.07000,
"Time": "2014-04-09T10:01:56",
"Id": 1
}];
Or, when inspected in Chrome console:
Whenever I feed my component with this array, the component works fine and all lines / axis are drawn correctly.
Second case: I fetch an array from my controller using d3.json, and get the following returned when logging it to console:
[{"Weight":0.0,"Speed":59.9,"Depth":362.24000,"Time":"2014-04-09T10:01:23","Id":0},{"Weight":10.0,"Speed":59.9,"Depth":394.07000,"Time":"2014-04-09T10:01:56","Id":1}]
So, whenever I'm trying to do a json.foreach() (json is the name of the array from controller):
json.forEach(function(d) {
var date = format(d.Time);
d.Time = date;
});
I get an error saying the following when starting the foreach function:
Uncaught TypeError: undefined is not a function.
In order for this to work, I had to do a JSON.parse(json) on the data returned from my controller through d3.json(), and then my array looks like the following:
I should also mention that my asp.net mvc controller returns this:
string json = JsonConvert.SerializeObject(Model.Trend.ToArray());
return Json(json, JsonRequestBehavior.AllowGet);
I get the fact that my array returned from controller looks like a string of values when inspecting it, but I really don't understand why.
So, I guess my question really boils down to this;
Why does my array "tmp" work, but my array fetched with d3.json needs to be parsed before working?
The 'tmp' array is parsed for you by the browser when the script is run. You can check this when you deliberately create a faulty array by for example place a double bracket somewhere.
Your browser will tell you it doesn't understand what you want the 'tmp' variable to be.
However, when you create a call to your MVC controller, it doesn't know beforehand what result type to expect from that controller. Maybe some other controller it will call later on in your application will return XML data, which needs another way of parsing.
An easier method to fetch JSON data from 'anywhere' is to use the jQuery .getJSON method.
This requires no extra call to parse the data.
Also, what does you D3 call look like? What function did you declare to handle the callback?
try
$.each(json, function (index, d) {
var date = format(d.Time);
d.Time = date;
});
I am trying to parse in this result of data which i obtained from xml conversion to json parsing :
var output = [{"SearchResults:searchresults":{"$":{"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","xsi:schemaLocation":"someurl","xmlns:SearchResults":"someurl"},"request":[{"keyval":["keydata"]",...}]}]}]}]}]}]}}]
How to get keydata of keyval. I tried parsing and stringify also but no results.
Thanks in Advance
Your unreadable comment does not really shed much light on the issue. My guess is that you retrieve JSON though AJAX with jQuery, thus your JSON is already decoded when you display it in the console (that's what jQuery is good at) and you no longer have a JSON string but good old JavaScript array. Your question is probably the classical "how do I read a deeply nested piece of data" we see a lot here.
Using proper indentation everything's cleaner:
var output = [
{
"SearchResults:searchresults": {
"$": {
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:schemaLocation": "someurl",
"xmlns:SearchResults": "someurl"
},
"request": [
{
"keyval": [
"keydata"
]",
...
First item of array:
output[0]
First key:
output[0]["SearchResults:searchresults"]
Next level:
output[0]["SearchResults:searchresults"]["$"]
... etc.
Folks,
Trying to understand returning and forming JSON responses.
The following code returns the object as a single string:
res.send(JSON.stringify(data));
Output to the browser:
{"Count":1,"Items":[{"dbsource":{"S":"x"},"number":{"S":"5002820"},"name":{"S":"blah,foo"},"expiration":{"S":"06/13/2015"},"type":{"S":"bar"}}]}
Dont I want the JSON output to be more readable, ie :
{
"one": "two",
"key": "value"
}
What should i change JSON.stringify(data) to? Ideally I want the response to be used as an API endpoint.
Thanks!
You are almost there. Use stringify with spaces
var str = JSON.stringify(data, undefined, 2);
The above string will have indentation with 2 spaces.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
I have encountered a bizarre case when attempting to parse some JSON data sent from a server.
The data is essentially, a set of rows of data - i.e. a list of lists, and looks something like this:
[[1,2,3],[4,5,6],[7,8,9]]
In FF (using Firebug), the received JSON data is valid, and renders correctly.
When I attempt to parse the JSON data using either of this statements, it fails:
JSON.parse()
code breaks on error
jQuery.parseJSON()
parses without complaining, yet the result of the parse is a null object
The only way I have managed to successfully parse the JSON response, is to use the dreaded eval() statements, which is a BIG security issue.
Anyone knows what may be going on?
I'm just starting my adventure with JavaScript and JSON, but it looks like it's not a valid JSON object. There is no key:value in this list of lists. I wold suggest changing it into list of obects containing list fields. Sth like:
[
{ list: [ 1, 2, 3 ] },
{ list: [ 1, 2, 3 ] },
{ list: [ 1, 2, 3 ] }
]
But I might be very wrong.