??yy 2016-10-29 21:21 采纳率: 0%
浏览 90

在json ajax中添加括号

I'm working with a plugin called (http://michaeleisenbraun.com/columns/) that converts json to tables.

I use the following code:

<script>
$.ajax({
      url:'/large-data.json',
      dataType: 'json', 
      success: function(json) { 
          example2 = $('#example2').columns({
              data:json, 
          }); 
      }
  });
</script>

It works well when the json is in brackets, like below:

[
  {
    "id": 9998,
    "isActive": false,
    "balance": "$5",
    "age": 38,
    "eyeColor": "blue",
    "name": "Lola Townsend",
    "gender": "female",
    "company": "...",
    "email": "asdf@asdf.com,
    "phone": "..."
  }
]

But, does not work if the json is not in brackets, like below:

  {
    "id": 9998,
    "isActive": false,
    "balance": "$5",
    "age": 38,
    "eyeColor": "blue",
    "name": "Lola Townsend",
    "gender": "female",
    "company": "...",
    "email": "asdf@asdf.com,
    "phone": "..."
  }

The json response is from other sites, so I will not be able to control whether it does / does not have brackets.

Is there a way to ensure the json returned has brackets each time and if not, that brackets are added?

I tried JSON.parse() and it did not work.

  • 写回答

2条回答 默认 最新

  • weixin_33698043 2016-10-29 22:09
    关注

    The first one mean it's an array object, the second one is only an object. I don't really get what you are trying to do right now but you can simply ass the object into in array if it's not allready one. something like :

    if(!Arrays.isArray(yourObject)) {
        var temp = [] ;
        temp.push(yourObject);
        yourObject= temp;
    } 
    

    I haven't test it since i don't know what you want to do, but this is the main idea.

    Hope it helps !

    • Nic
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序