0

I am new in javascript, can you please help me convert from JSON format to a normal array

             {"data": [
             {"name": "Bhengu","surname":"Nathi"},
             {"name": "Tsunami","surname":"Msipha"},
             { "name": "Fish","surname":"Lee"}
             ]};


             data= [
             {name: Bhengu, surname: Nathi},
             {name: Tsunami, surname: Msipha},
             { name: Fish, surname: Lee}
              ];
Fish123
  • 25
  • 1
  • 2
  • 6

3 Answers3

2

you can use json_decode function of php

$json = '{"data": [{ "name": "Bhengu","surname":"Nathi"}, { "name": "Tsunami","surname":"Msipha"}, { "name": "Fish","surname":"Lee"} ]}';
$data = json_decode($json);
var_dump($data);

output will be :

object(stdClass)[1]
  public 'data' => 
    array
      0 => 
        object(stdClass)[2]
          public 'name' => string 'Bhengu' (length=6)
          public 'surname' => string 'Nathi' (length=5)
      1 => 
        object(stdClass)[3]
          public 'name' => string 'Tsunami' (length=7)
          public 'surname' => string 'Msipha' (length=6)
      2 => 
        object(stdClass)[4]
          public 'name' => string 'Fish' (length=4)
          public 'surname' => string 'Lee' (length=3)
Poonam
  • 4,591
  • 1
  • 15
  • 20
1
{"data": [{ "name": "Bhengu","surname":"Nathi"}, { "name": "Tsunami","surname":"Msipha"}, { "name": "Fish","surname":"Lee"} ]};

heredata= [ { name: Bhengu, surname: Nathi}, { name: Tsunami, surname: Msipha},{ name: Fish, surname: Lee} ];

you can use Json2 script

you can then run:

var myObject = JSON.parse(myJSONtext, reviver);

which should give you the array you need as myObject

elixenide
  • 44,308
  • 16
  • 74
  • 100
Liam
  • 27,717
  • 28
  • 128
  • 190
  • The code i've been running does not work on json format and works on this one heredata= [ { name: Bhengu, surname: Nathi}, { name: Tsunami, surname: Msipha}, { name: Fish, surname: Lee} ]; – Fish123 Mar 07 '12 at 10:54
  • If the question is, I need to convert Json into an array the JSON.Parse sould work. If you want to convert Json into another string format then you will need to parse it yourself. What I think your saying is that you declare an array using heredata= [ { name: Bhengu, surname: Nathi}, { name: Tsunami, surname: Msipha}, { name: Fish, surname: Lee} ]; so heredata is an array! The above example sets myObject as an array also, heredata and myObject are an array of the same type? That said I'm a bit confused by what your actually asking.... – Liam Mar 07 '12 at 11:09
0

Use json_decode() with the second parameter true, which will force the returned objects to be converted to arrays.

$result = json_decode($jsonStr, true);
if (isset($result)) {
  do something here...
}

Check the manual entry for detailed use (ex. the $depth parameter).

binar
  • 1,197
  • 1
  • 11
  • 24