JSON Fields are Undefined (Javascript) - javascript

I'm getting JSON from a servlet and turning the responseText into a JSON object by using JSON.parse(). Chrome Developer Tools shows the JSON object as having the data that I want, but when I actually try to access it I just get a bunch of 'undefined's.
Am I not interpreting the data correctly?
Screenshot of Chrome Developer Tools:
And briefly, my code to output the data:
for (var i = 0, len = jsonObj.length; i < len; ++i) {
// Setup the result...
var resultRow = document.createElement("tr");
resultsTable.appendChild(resultRow);
var result = jsonObj[i];
// Name
var coverCell = resultRow.insertCell(0);
coverCell.innerHTML = result.name;
}
jsonData as seen in the screenshot is passed into the output function as jsonObj.

The key you are trying to access seems to have the # character at the front. Since the # character is not a valid identifier and therefore you can't use dot-notation, you can retrieve the value by using bracket notation:
coverCell.innerHTML = result['#name'];

if you are getting json from the server then why are you using json.parse()? you should directly use the data as a json.
JSON.parse() is used to parse string into JSON. i undertand the response from the server is already a JSON which can used directly without further parsing.
and as a way of troubleshooting you can use console.log to print the object.

Related

Json Keys Are Undefined When Using Them From Script Tag

I've been trying to load certain Json with Ajax GET request and then parsing it.
However when trying to access the Json key from HTML script tag it was undefined.
In order to debug this issue, I logged all the keys of Json in console as well as the Json itself. Therefore i utilized this function:
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, "); // Explanation is below
console.log(invList[0]) // Just testing with first object
console.log(Object.keys(invList[0]));
});
}
getInv();
Purpose of data.split(",, "):
Since my backend script uses different programming language, I had to interpret it to the one suitable for Javascript.
There also were multiple Json objects, So i separated them with ",, " and then split them in Javascript in order to create a list of Json objects.
After calling the function, Following output was present:
Although the interesting part is that after pasting Json object in console like this:
This was the output:
So basically, in script tag, i was unable to access object's keys, although once i used it manually in console, all keys could be accessed.
What could be the purpose behind this? It seems quite strange that different outputs are given. Perhaps invList[0] is not Json object at all in the script tag? Thanks!
data.split() returns an array of strings, not objects. You need to use JSON.parse() to parse the JSON string to the corresponding objects.
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, ");
console.log(invList[0]) // Just testing with first object
var obj = JSON.parse(invList[0]);
console.log(Object.keys(obj));
});
}
You can use .map() to parse all of them, then you'll get an array of objects like you were expecting:
var invList = data.split(",, ").map(JSON.parse);

How to parse an array from a JSON string?

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.

Concatenate json arrays from localStorage and send to PHP

I am using localStorage to store some json arrays (no more than 25), and when the user logs out, I need to save the information stored in a MySQL database. Therefore, I am sending the data to a PHP script that is in charge of communicating and dealing with all the database stuff.
Anyway, I have been searching on the web, and I found here - Merge two json/javascript arrays in to one array - that I could just use concat.
I basically use this function:
function saveEverything() {
var localStorageData = "";
for (var i=0; i < localStorage.length; i++) {
localStorageData = localStorageData.concat(localStorage.getItem(localStorage.key(i)));
}
...
}
The ... represents the ajax bit that sends the localStorageData to a PHP script.
As you should know, localStorage doesn't store anything but strings, so I have to do JSON.stringify when I am setting the items. You might have noticed that I didn't do JSON.parse when concatenating the localStorage items into the localStorageData variable. I tried that before, and when I did alert(localStorageData) I only got [Object][object] ... (or something like that).
Anyway, with this kind of approach I am sending strings to php, and each json array is separated by line break. Is this the best/correct thing to do or should I have sticked to the JSON.parse way?
What does your JSON look like? concat is a method of Array instances, so you can only do this when you're working with an Array. Furthermore, JSON is a notation, to use it like this you would have to parse it back into JavaScript and then out again.
For example,
var json1 = '[{"foo":"bar"}]',
json2 = '[{"fizz":"buzz"}]';
var mergedJS = JSON.parse(json1).concat(JSON.parse(json2)),
mergedJSON = JSON.stringify(merged);
mergedJSON; // '[{"foo":"bar"},{"fizz":"buzz"}]'
If they're not Arrays, you might be able to get away with just wrapping them (depending on how you want the result), i.e.
var json1 = '{"foo":"bar"}',
json2 = '{"fizz":"buzz"}';
var mergedJSON = '[' + json1 + ',' + json2 + ']';
mergedJSON; // '[{"foo":"bar"},{"fizz":"buzz"}]'
Finally,
You might have noticed that I didn't do JSON.parse when concatenating the localStorage items into the localStorageData variable. I tried that before, and when I did alert(localStorageData) I only got [object Object]
[object Object] is the result of calling toString on almost any Object.
({}).toString(); // "[object Object]"
If you want to see something useful, use console.log and view the Console, or convert back to String with JSON.stringify.
alert(localStorageData) I only got [Object][object]
That's normal, you should stick with this previous version, build an object of objects and in the end use
JSON.stringify(localStorageData)
to send it as string.
function saveEverything(){
var localStorageData = {},
l = localStorage.length,
k;
for (var i=0; i < l; i++) {
k = localStorage.key(i);
localStorageData[k] = JSON.parse(localStorage.getItem(k));
}
return localStorageData;
}
Using object also makes it easier to distinguish these arrays, since you can also save keys under which they were saved.

Passing (and parsing!) JSON objects through MVC4

I'm confused as to how I should be using JSON objects within MVC and how they should passed from Controller, to View, to Jscript.
I'm also not sure if I'm correctly parsing the JSON objects at the right points...
My controller is returning a PartialView with a json object ("Variables" is a list of data e.g. Id=2012, Name=BillyJoel, Value="£2,000"):
public ActionResult JavascriptConstants() {
var variables = Service.Obtain<VariableService>().All().ToList();
var json = new JavaScriptSerializer().Serialize(variables);
return PartialView("JavascriptConstants", json);
}
My View then makes this data available to my scripts by creating this variable:
#model string
...
var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))';
My Jscript file then accesses the data and attempts to pull out the information and key value pairs, but seems to be interpreting the JSON as a string:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
for (var variable in variableList) {
alert(variableList[variable]);
}
This just returns alerts of ", [, {, etc. as each character of the string is displayed. How do I access the key values of the JSON object?
I've tried changing my JS to use:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
But this just gives me an Uncaught SyntaxError: Unexpected token I error in my browser (I'm assuming when it hits the "I" of "Id).
Any help much appreciated, thanks.
I found the issue:
The issue was the use of JavaScriptSerializer().Serialize(foo) as this was creating a JSON object that contained newlines and tabs instead of replacing them with \n and \t.
$.parseJSON() cannot handle newlines and so throws up unexpected token error.
This was corrected by importing the JSON.NET package and using :
var json = JsonConvert.SerializeObject(variables);
This passed a JSON object with newlines and tabs replaced with \n's and \t's. Which can then be made accessible to the View using:
#model string
...
var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))';
and finally in the script using:
var variableList = $.parseJSON(mvcListOfVariablesInDB)
Hope this helps someone else one day...

javascript get nested array elements

in javascript how do I get individual elements out of this array?
http://pastebin.com/n8yrnCpf
I need to loop through it and format the data
how would I get array[0][1][1], for instance
and perhaps there is some json script for doing it quickly
Json comes from J ava S cript O bject N otation. It's a javascript-compatible format, so you can loop through it, and access it as you need. In other words, you do can get array[0][1][1].
If what you're asking for is how can you receive a JSON in a string and convert it to an "usable" JavaScript variable, you can do that this way:
var json_string = "[[['whatever','and'],['more','whatever']]]"
var parsed_json = JSON.parse (json_string)
console.log (parsed_json[0][0])
Or, if you use old browsers (IE7 and so), you can use JQuery and its elder-safe function parseJSON:
var json_string = "[[['whatever','and'],['more','whatever']]]"
var parsed_json = $.parseJSON (json_string)
console.log (parsed_json[0][0])

Categories

Resources