Reputation: 2305
I have the following class in C#:
public class Caption
{
public string line;
public string timestamp;
}
I have created some Caption objects and added them to a List:
List<Caption> CaptionList = new List<Caption>();
var obj = new Caption
{
line = "Some text"
timestamp = "00:10"
};
CaptionList.Add(obj);
I then use Json.NET to serialize the list to Json, like this:
public string json = JsonConvert.SerializeObject(CaptionList);
Now I want to use this as a JavaScript array, so I tried this:
var arr = '<%=json%>';
I don't have much JavaScript knowledge, but it seems like arr
is now a string and not an array because json
is in fact a C# string. I tried accessing the objects by using arr[i].line
etc, but that doesn't work.
How do I make the json
an actually array in JavaScript?
Upvotes: 2
Views: 8118
Reputation: 2403
We use MVC and in our views (which pass up models) we use a simple line whenever we want to convert the model into a javascript object:
<script type="text/javascript">
$(document).ready(function () {
MyObject.Initialize(@Html.Raw(Json.Encode(Model)));
});
</script>
The key to all of that being:
@Html.Raw(Json.Encode(Model))
"Model" is what MVC passes up but you could very easily do something like this: (Razor syntax)
@{
List<Caption> CaptionList = new List<Caption>();
var obj = new Caption
{
line = "Some text"
timestamp = "00:10"
};
CaptionList.Add(obj);
}
then...
<script type="text/javascript">
$(document).ready(function () {
MyObject.Initialize(@Html.Raw(Json.Encode(CaptionList)));
});
</script>
I haven't tested this but it should work, or some variation of it, you may need to put "CaptionList" as a property in some parent object and pass that into Json.Encode.
You could do this instead, as well:
<script type="text/javascript">
$(document).ready(function () {
var myArray = @Html.Raw(Json.Encode(CaptionList)));
});
</script>
Note that jQuery isn't necessary here, it was just a way to wrap it up in the ready function.
Upvotes: 2
Reputation: 700212
You can use the JSON.parse
method to parse the JSON string into an array:
var arr = JSON.parse('<%=json%>');
However, as JSON is a subset of JavaScript syntax, you can actually use the JSON as a JavaScript array literal:
var arr = <%=json%>;
Upvotes: 4
Reputation: 2090
Take it as demo
Your variable arr
will be rendered like this. This will be string. so to convert a string into JSON Object you need to parse that string. by using JSON.parse(arr)
var arr = '[ { "line":"Some text", "timestamp":"00:10" }, { "line":"Some text", "timestamp":"00:10" } ]';
var JObject= JSON.parse(arr);
Now you can access JObject[0].line
This will give you
"Some text"
You can take a look Here at Mozilla
Upvotes: 2