Parsing JSON data in javascript - javascript

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.

Related

JSON to Object - JavaScript

I am trying to take a JSON list that is formatted as such: (real list has over 2500 entries).
[
['fb.com', 'http://facebook.com/']
['ggle.com', 'http://google.com/']
]
The JSON list represents: ['request url', 'destination url']. It is for a redirect audit tool built on node.js.
The goal is to put those JSON value pairs in a javascript object with a key value array pair as such:
var importedUrls = {
requestUrl : [
'fb.com',
'ggle.com'
],
destinationUrl : [
'https://www.facebook.com/',
'http://www.google.com/'
]
}
Due to the sheer amount of redirects, I do prefer a nonblocking solution if possible.
You first need to create your object:
var importedUrls = {
requestUrl: [],
destinationUrl: []
}
Now, let's say you have your data in an array called importedData for lack of a better name. You can then iterate that array and push each value to its proper new array:
importedData.forEach(function(urls){
importedUrls.requestUrl.push(urls[0]);
importedUrls.destinationUrl.push(urls[1]);
});
This will format your object as you want it to be formatted, I hope.
I will propose it to you that you take another approach.
Why not have an array of importedUrls, each one with its correspondent keys?
You could have something like:
importedUrls = [
{
requestUrl: 'req',
destinationUrl: 'dest'
},
{
requestUrl: 'req2',
destinationUrl: 'dest2'
},
]
I'm sure you can figure out how to tweak the code I showed to fit this format if you want to. What you gain with this is a very clear separation of your urls and it makes the iterations a lot more intuitive.

JSON parse functions are not parsing

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\" }]"

Why does my array need parsing, when they look the same in the console?

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;
});

How to parse json which is parsed from xml conversion inside javascript?

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.

Querying/Searching for Values within JSON

For a web site I'm creating, I have to create a quote based on data provided as a JSON string from the server. I've been looking through this site (and various others) but still am unsure on the best way to query/search the data.
For example, I need to get the Area Name from the Area ID. I need to get the maximum age for an area and also the price for a given minimum/maximum age.
I also want to get an array of prices.
Is it best to create a Javascript object from the string using the eval method? Or should I be using jQuery.
Thanks for your help.
({"SkiPass":[{"Id":1,"Area":"Chamonix","Rates":[{"Id":1,"AgeMin":0,"AgeMax":2,"Price":2.5},{"Id":2,"AgeMin":3,"AgeMax":17,"Price":5.0},{"Id":3,"AgeMin":18,"AgeMax":30,"Price":6.2},{"Id":4,"AgeMin":31,"AgeMax":59,"Price":7.4}]},
{"Id":2,"Area":"Megeve","Rates":[{"Id":1,"AgeMin":0,"AgeMax":2,"Price":1},{"Id":2,"AgeMin":3,"AgeMax":17,"Price":2.0},{"Id":3,"AgeMin":18,"AgeMax":30,"Price":2.2},{"Id":4,"AgeMin":31,"AgeMax":59,"Price":4.4}]},
{"Id":3,"Area":"Verbier","Rates":[{"Id":1,"AgeMin":0,"AgeMax":2,"Price":1.5},{"Id":2,"AgeMin":3,"AgeMax":17,"Price":3.0},{"Id":3,"AgeMin":18,"AgeMax":30,"Price":4.2},{"Id":4,"AgeMin":31,"AgeMax":59,"Price":5.4}]}]})
Create a JavaScript object from the string, most definitely, but do it with legitimate JSON parsing facilities and not "eval()". You could use jQuery, but there are other solutions, such as the JSON tools available from json.org, which are small and simple.
Once it's a JavaScript object, well then your needs should guide you as to whether some query solution is necessary, or instead that it's just a simple matter of programming.
I think the best method is jLinq: http://hugoware.net/Projects/jLinq it's like doing a SQL query on JSON.
It doesn't needs jQuery.
I use it, and it's great.
Create the object from the JSON string using JSON.parse() or jQuery.parseJSON() if you are already using jQuery -- or just pass it as from the server side as JSON.
You can then iterate through the object to find the record you want. Or, you can use build your objects so that you can naturally grab data from them.
FloatLeft - as Dan points out, your task would be much easier if you could use XPath but there is no need to re-write your data in XML format. With DefiantJS (http://defiantjs.com) you can now query JSON structure with XPath expressions.
DefiantJS extends the global object JSON with the method "search", which enables XPath queries and returns an array with the matches (empty array if no matches were found). The returned array is equipped with aggregate functions as well; one of these "sortDesc".
Check out this working fiddle;
http://jsfiddle.net/hbi99/H3PR3/
var data = {
"SkiPass": [
...
{
"Id": 3,
"Area": "Verbier",
"Rates": [
{ "Id": 1, "AgeMin": 0, "AgeMax": 2, "Price": 1.5 },
{ "Id": 2, "AgeMin": 3, "AgeMax": 17, "Price": 3 },
{ "Id": 3, "AgeMin": 18, "AgeMax": 30, "Price": 4.2 },
{ "Id": 4, "AgeMin": 31, "AgeMax": 59, "Price": 5.4 }
]
}
]
},
res1 = JSON.search( data, '//SkiPass[Id=3]/Area' ),
res2 = JSON.search( data, '//*[Area and Id=3]/Rates' )
.sortDesc('AgeMax'); // <-- sorting descending by the value of "AgeMax"
document.getElementById('name').innerHTML = res1;
document.getElementById('max_age').innerHTML = res2[0].AgeMax;
document.getElementById('price').innerHTML = res2[0].Price;

Categories