如何使用 jquery 解析存储在 viewBag 中的 jsonarray

How to parse a jsonarray stored in a viewBag using jquery

我无法解析 viewBag 中的 json数组。我想获取内容,然后使用它们向

添加选项

使用 console.log 我可以看到我的 json 如下:

到目前为止我有一个只有一个元素的数组

[  
   {  
      "BackgroundColor":null,
      "BaseFormat":"PNG",
      "ColorFormat":"RGB",
      "ColorProfile":null,
      "Density":"300",
      "Extra_param":null,
      "FileFormat":"JPG",
      "PresetId":"2",
      "Resolution":"",
      "Quality":100
   }
]

我在一个变量中有如下内容:

var presetArray = @Html.Raw(Json.Encode(@ViewBag.user_doc_presets)); console.log(presetArray);

我想获取要用于 select 的 BaseFormat 和颜色格式。

我尝试了一些 Whosebug 但他们没有帮助我。

如果您有 link 到旧的 post 或提示,请分享。 @downvoters,如果您对此有任何疑问,请告诉我 post 而不是暗中投票。

因为它是数组类型,你可以用它的 Index 访问它,这里是 0 因为数组元素只有一个。

presetArray[0].BaseFormat
presetArray[0].ColorFormat

var presetArray  = [{"BackgroundColor":null,"BaseFormat":"PNG","ColorFormat":"RGB","ColorProfile":null,"Density":"300","Extra_param":null,"FileFormat":"JPG","PresetId":"2","Resolution":"","Quality":100}]



console.log("Base Format: " + presetArray[0].BaseFormat);
console.log("Color Format: " + presetArray[0].ColorFormat);

我少了一个Json.Parse,问题解决了

请参考 http://jsfiddle.net/jresdqw3/

var arr = [  
   {  
      "BackgroundColor":null,
      "BaseFormat":"PNG",
      "ColorFormat":"RGB",
      "ColorProfile":null,
      "Density":"300",
      "Extra_param":null,
      "FileFormat":"JPG",
      "PresetId":"2",
      "Resolution":"",
      "Quality":100
   }
];

alert(arr.length);
alert(JSON.stringify(arr).length);