在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.

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

You can use regex to check if the code is correct with ^\[| *\]$. You should have 2 matches if the first character of the string is [ and the last is ].

You can test here : https://regex101.com/r/Cukwog/1