【问题标题】:How to parse a jsonarray stored in a viewBag using jquery如何使用 jquery 解析存储在 viewBag 中的 jsonarray
【发布时间】:2018-11-16 14:25:52
【问题描述】:

我无法解析 viewBag 中的 jsonArray。我想获取内容,然后使用它们将选项添加到

使用 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);

我想将 BaseFormat 和 colorformat 用于选择。

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

如果您有旧帖子的链接或提示,请分享。 @downvoters,如果您对这篇文章有任何疑问,请告诉我,而不是暗中投反对票。

【问题讨论】:

  • console.log(presetArray[0].BaseFormat); ...你试过了吗?
  • 但是 TBH 如果你想将它们放入一个选择中,为什么不直接在 MVC/Razor 代码中创建和填充选择呢?这似乎是一个稍微复杂的方法。
  • @ADyson,我确实尝试了 presetArray.length,它给了我惊人的 184,这就是我迷路的原因。我会尝试更多
  • 这可能是因为它仍然是一个字符串....184 是 JSON 包含的字符数(请参阅jsfiddle.net/jresdqw3)。您应该能够让 MVC 立即将其作为文字输出。如果失败,请在 JS 中使用 JSON.parse() 将其转换为数组,然后再尝试使用它。
  • @ADyson,你是对的,我可以从服务器端做到这一点,但我需要 jsonArray 来填充更多的 html 元素,客户可以根据自己的意愿谨慎修改。跨度>

标签: javascript jquery json razor html-helper


【解决方案1】:

由于它是数组类型,您可以使用它的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);

【讨论】:

    【解决方案2】:

    我缺少一个 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2013-06-12
      • 2023-01-03
      相关资源
      最近更新 更多