Home > other >  How to remove Square Bracket from JSON in JavaScript or in php?
How to remove Square Bracket from JSON in JavaScript or in php?

Time:02-17

I have some JSON data, it is apairing like this now

[
  [
    {
      'key': 'value'
    },
    {
      'key': 'value'
    }
  ]
]

What I want to do, is remove the second square bracket from here like this:

[
  {
    'key': 'value'
  },
  {
    'key': 'value'
  }
]

I've applied some algorithms in both PHP and javascript but it does not work please help me if you know how to solve this

CodePudding user response:

You can use the array_merge() PHP method like this (PHP 7.4 or above)

EDIT: Decode the JSON string using json_decode() php function before.

$flattened_array = array_merge(...$arr);

https://wiki.php.net/rfc/spread_operator_for_array

https://www.php.net/manual/pt_BR/function.array-merge.php

Or simply do this:

$arr = "[
  [
    {
      'key': 'value'
    },
    {
      'key': 'value'
    }
  ]
]" //receives a JSON string;

$flattened_arr = json_decode($arr[0]) //decodes it;
  • Related