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...
Related
I would like to assign an array from Laravel to a JavaScript array. I have gotten the array from my AppServiceProvider and json_decoded it like:
View::composer('*', function($view)
{
$users = Users::all();
$view->with(compact(users );
}
I then access my $usersArray from my javascript file like:
var dataSet = JSON.parse({!!$users !!});
I am however getting the following error;
jQuery.Deferred exception: Unexpected token o in JSON at position 1 SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
Since you're encoding it in the server side, you need to decode it in the client side like:
$chequesArray = Users::all()->toJson();
var dataSet = JSON.parse({!!json_encode($chequesArray)!!});
Or also Using "base64_encode" to conserve the json format like:
$chequesArray = base64_encode(Users::all()->toJson());
var dataSet = JSON.parse(atob('{{$chequesArray}}');
The main difference comes from the use of {{ }} vs {!! !!}, the first one escapes the special chars so it will turn the quotes "" to " then the JS will be unable to parse the string (that why we can use `base64_encode``to conserve the format), the second one will conserve the format and allow the quotes what gives the JS part the ability to parse it simply.
var dataSet = #php $chequesArray #endphp;
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);
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 working on a parser for a text file. I am trying to parse some JSON strings into objects so I can easily display some different values on a webapp page (using flask). I am passing the strings into my html page using jinja2, and trying to parse them objects in javascript.
function parseLine(x) {
var obj = JSON.parse(x);
document.write(obj.timestamp1);
}
I am getting this error:
SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data
in the console browser. I have found many stackoverflow questions with that error, but the suggestions do not fix my problem.
If I use a dummy string, surrounded by single quotes: '{"test": "1234"}' it works fine.
If I need to include anymore information I can.
Had similar issues but was able to solve it using this way using the
reviver parameter on JSON.parse()
var Person = {}
// an empty person object
//sample json object, can also be from a server
var sampleJson = {'name': 'Peter', 'age': "20"};
//use the javascript Object.assign method to transfer the json from the source[JSON.parse]to the target[Person]
// the source is JSON.parse which take a string argument and a function reviver for the key value pair
Object.assign(Person, JSON.parse(JSON.stringify(sampleJson),
function (k, v) {
//we return the key value pair for the json
return k, v
}
)
)
console.log(Person.name) //Peter
console.log(Person.age) // age
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.