-1

I've got an ICollection<T> of POCO like this:

public class SearchJsonModel
{
   public string label { get; set; }
   public string category { get; }
}

In my Razor view, i serialize it as follows:

<script type="text/javascript">
   var jsonArray = @Html.Raw(Json.Encode(Model));
</script>

But the output is this:

var jsonArray = [
   {"category":"Names","label":"Joe"},
   {"category":"Names","label":"John"}
];

Which is causing problems because of the quotes around the properties.

I need to access the properties of each JSON object, so I would expect it to be like this:

var jsonArray = [
   {category:"Names",label:"Joe"},
   {category:"Names",label:"John"}
];

That way i can do something like this:

$.each(jsonArray, function(index, item) {
   var x = item.category;
});

What am i doing wrong? Am i using the wrong method to encode?

RPM1984
  • 72,246
  • 58
  • 225
  • 350

2 Answers2

2

This JSON is valid (checked in JSONLINT). The quotes should be there.

You can get the category values like this without any problem

$(function(){
   var data=[
   {"category":"Names","label":"Joe"},
   {"category":"Names","label":"John"}
];

    $.each(data,function(index,item){
          alert(item.category);
    });        

});​

Sample http://jsfiddle.net/DKnBh/

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • 1
    /me slaps head. Was a ordering problem with my encoding and script to consume it. Sorry for wasting everones time. :) – RPM1984 Aug 08 '12 at 01:20
0

This is standard JSON and shouldn't cause a problem.

See here for more info: in JSON, Why is each name quoted?.

Community
  • 1
  • 1
Garrett Vlieger
  • 9,354
  • 4
  • 32
  • 44