weixin_33681778 2010-10-25 21:33 采纳率: 0%
浏览 58

用Javascript解析JSON

I have a webservice (RestEasy) returning a JSON object containing a List<..> element. I am trying to parse the results in a Javascript for loop. If the List<> element has 2 or more elements, all is well. If the List<> element has only one element, the Javascript loop breaks.

This is because the JSON respresentation actually changes when there is only one element. For example:

{"parent":[{"a":1},{"b":2}]}

works just fine ... but for some reason, the JSON looks like this for one child:

{"parent":{"a":1}}

Note ... that the array indicator [] is missing.

Is that standard JSON? This type of notation forces ugly, unnecessary checks in my javascript for existence or size, etc of an expected array ...

Is this consistent standard practice? Why doesn't JSON return a list of one?

{"parent":[{"a":1}]}

Is this possibly an artifact of my server side and would other server side generators actually build a different JSON representation? I even tried to use dojo.forEach and it works great until it reaches the single element array that unfortunalty, lacks any type of list notation.

  • 写回答

4条回答 默认 最新

  • weixin_33691700 2010-10-25 21:36
    关注

    This is an artifact of your server side. Might be your framework supplies the datastructure to the JSON generator in this way, I guess it's not the problem of the generator itself.

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧