Could you please help me find what I am doing wrong?
My model has a string[] field called AllKnownColors. I am trying to use it in my javascript code like this:
var clrs = JSON.parse('#Html.Raw(Model.AllKnownColors)');
But it doesn't work. The debugger shows me this:
var clrs = JSON.parse('System.String[]');
and the following error: Uncaught SyntaxError: Unexpected token S
And I cannot figure out what is wrong.
Thanks.
The code
var clrs = JSON.parse('#Html.Raw(Model.AllKnownColors)');
is similar to
var clrs = JSON.parse('#Html.Raw(Model.AllKnownColors.ToString())');
You need to convert Model.AllKnownColors to json. You can use Newtonsoft JSON for this purpose.
var clrs = JSON.parse('#Html.Raw(JsonConvert.SerializeObject(Model.AllKnownColors))');
Or you can write you own method for converting. Newtonsoft JSON is easy and good choice. Your own methods could be more fast.
Model.AllKnownColors is a string array. Html.Raw accepts a single string as an argument. Since Model.AllKnownColors is not a string, C# framework calls the object's ToString method. By default, ToString returns the name of the object type.
If you are attempting to use a pure string of colors, you can do something like this instead:
var clrs = '#string.Join(", ", Model.AllKnownColors)';
If you actually want to turn Model.AllKnownColors into a JavaScript array, you can do this:
var clrs = #Html.Raw(Json.Encode(Model.AllKnownColors));
Note that in both cases, JSON.parse is unnecessary.
Related
I'm doing some extensive testing to learn how PHP and JS variables, objects, arrays etc can be passed to one another successfully. There's a lot of confusing questions / answers on this subject.
As far as my testing has shown, I can create a variety of PHP objects:
$testarray = ["this", "is", "me"];
$testobject = (object) array("this"=>"that", "is"=>"was", "me"=>"him");
$teststring = "this is me";
$testint = 9758.25;
and then I can pass them through json_encode() (still in PHP)
echo '<script>
var testarray = '.json_encode($testarray).';
var testobject = '.json_encode($testobject).';
var teststring = '.json_encode($teststring).';
var testint = '.json_encode($testint).';
</script>';
and when run, this results in:
<script>
var testarray = ["this","is","me"];
var testobject = {"this":"that","is":"was","me":"him"};
var teststring = "this is me";
var testint = 9758.25;
<script>
I just want to confirm that this result is, and always will be, perfectly valid JavaScript? I can't see anything wrong with it, yet some sources recommend the use of JSON.parse(). Is this needed in this context?
I know that if an array or object in JS was passed through JSON.stringify(), I'd have to parse it.
I also know that to send objects or arrays from JS to PHP, I'd have to use JSON.stringify() and json_decode() to make them valid, but it seems that json_encode() results in valid JS without having to use JSON.parse()?
Yes it is valid, because JSON syntax is a subset of JavaScript object literal syntax. Therefore if you inject JSON-encoded text into generated JS code in the way you've shown then it behaves as an object literal, just as if you'd written it there by hand.
JSON.parse would be required if you were receiving a string containing JSON-encoded text into a JavaScript variable (e.g. as the result of an AJAX request) and needed to convert it from a string into a usable object.
I have a string that looks like this:
"["Software","3rd Party"]"
How can I convert this to an object in javascript?
I familiar with converting HTML Entities to DOM Objects:
$("<div/>").html(encodedStr).text();
My situation is a little different than the one above. I don't want to create HTML, I need to create an object.
Use the built-in JSON.parse:
var jstr = $("<div/>").html(encodedStr).text();
var obj = JSON.parse(jstr);
Since you're using jQuery anyway, you can use $.parseJSON() instead of JSON.parse() if you need to support browsers older than IE8. (jQuery simply calls JSON.parse() when it's available.)
You can use "he" library with JSON.parse. "he" can encode and decode HTML code.
var str = he.decode("["Software","3rd Party"]");
var obj = JSON.parse(str);
How do I add quotation marks to a JSON Object attributes for example like this:
{name:"User 01"}
so it should look like that afterward:
{"name":"User 01"}
both of them are strings
JSON.stringify(eval('{name:"User 01"}'));
Not really great but works.
Assuming the first example is a Javascript object, you could convert it into a JSON string using JSON.stringify:
JSON.stringify({name:"User 01"});
outputs: "{"name":"User 01"}"
Assuming String
If the first example is a string, I think you would have to parse through it with methods like split.
the first notation
var string = {name:"user 01"}
if you use it then you can directly access all the properties and methods of the string object
but if you use this notation :
var string = {"name":"user 01"}
then you have to use :
window.JSON.parse("'"+string+"'")
Update:
Now that we have ES6, you can use template literals :
window.JSON.parse(`'${string}'`)
in order to access all the methods and properties of string object
the last notation is used generally when getting data back from php script
or something like that
Use this:
function JSONify(obj){
var o = {};
for(var i in obj){
o['"'+i+'"'] = obj[i]; // make the quotes
}
return o;
}
console.log(JSONify({name:'User 01'}));
Here is my question:
in java script:
we hav an object:
var someObject={"name":"somename"};
Now we want to get the name ,we ll do
alert(someObject.name); //it will print somename Right?
Same object i get from a source which sends a JSON object as
someJSONObject={"name":"someName"};
Now in my javascript code ,without parsing this someJSONObject ,i can get name as
alert(someJSONObject.name);
If it is so ,why we need to convert JSON Object to a javaScript Object by parsing it ,when we can use it as an object without parsing or using eval()?
Thanks !
Because it's not a JSON Object. The syntax {"name":"someName"}, with quoted keys, does not make it JSON, the same syntax is supported by Javascript object literals.
JSON can be embedded in Javascript strings. Like:
var json = '{"key": "value"}';
Then you can parse it into Javascript data types:
var obj = JSON.parse( json );
Note that eval may cause syntax errors because the syntaxes of JSON and Javascript are not ultimately compatible. The above would have caused a syntax error if evaled.
JSON is a string, so it's something like var jsonObject = '{"name":"someName"}'; an object is an object.
'[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]'
When I try to access the above like this:
for (var i = 0; i < data.length; i++) {
alert(data[i]);
}
It spells out each thing, such as [, {, ", S, and etc.
I also tried doing data[i].SponsorName but obviously got undefined. How should I be accessing this?
You need to parse the JSON string, preferably with JSON.parse. The JSON API is built into more modern browsers and can be provided to older browsers by including Crockford's JSON script. Crockford's script will detect if the browser already provides the API and adds it if not.
With that in place, if your JSON is in a string variable named response, you can:
var parsedResponse = JSON.parse( response );
//run your iterating code on parsedResponse
You would first need to eval() or more ideally JSON.parse() the JSON string in to a Javascript object. This assumes you trust the source of the JSON.
var jsonobj = JSON.parse(data);
// Now view the object's structure
console.dir(jsonobj);
Here's what it looks like after being evaluated and printed out:
var array = JSON.parse('[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]')
array[0].AccountingManager; // "me"
Or everyone's favorite library, since IE7 and below don't have native support:
$.parseJSON('[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]')
You parsed the Json string first, right?
var data = '[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]';
data = JSON.parse(data);
alert(data.SponsorName);
JSON.parse, when available, is the preferred method over "eval" because of security and performance issues.
You've got a JSON array followed by an object:
var data = [{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}];
alert(data[0].SponsorID);