1

It may seems silly question, I am little newbie here for JSON and trying to access the below JSON data in my JS file

[
    {
        "1": [
            "video1",
            "ENG"
        ]
    },
    {
        "2": [
            "video2",
            "CHI"
        ]
    }
]

But I am not able to access I have tried console.log(data[1]) and console.log(data[2]) but it did not work.

I need to create a new variable like this (so probably I need the for loop but before I use for loop I need to know how to access this JSON )

new_data =  "tracks: [{ 
            file: "video1", 
            label: "ENG"

       },{ 
            file: "video2", 
            label: "CHI"
        }]"

for little bit background how I created the JSON, I used below code to generate JSON in PHP from an array

This was the PHP array I had

Array ( [0] => stdClass Object ( [vid] => 1 [video_name] => video1.mp4 [sub_path] => http://abc.example.com/files/eng.vtt [sub_lang] => ENG [status] => 1 ) [1] => stdClass Object ( [vid] => 2 [video_name] => video2.mp4 [sub_path] => http://def.example.com/files/china.vtt [sub_lang] => CHI [status] => 1 ) )

Then I converted it to JSON and made a ajax call in my JS to get JSON data

  foreach ($querystring as $key => $value) {
           $cdn_sub_data [] = array($key+1 => array($value -> sub_path, $value -> sub_lang ));
        }

print json_encode($cdn_sub_data);

Help me where I am doing wrong !!! Thank you

Hitesh
  • 4,098
  • 11
  • 44
  • 82
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Mar 31 '14 at 15:21
  • http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript – pj013 Mar 31 '14 at 15:23

3 Answers3

2

Use:

var data = JSON.parse(ArrayHere);
console.log(data);
data.something = "hello";

And back is

var JSON = JSON.stringify(data);
0

data is wrapped in an array with one element. You would use data[0]["1"][0] to get "data1", for example.

You could also build the JSON you're emitting in such a way so as to prevent wrapping it in an entire array or wrapping it in an array with element tracks instead of using a numeric key (which should force conversion to an object).

array("tracks"
    => array(
        array(
            "file" => "video1",
            "label" => "ENG",
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

You should use JSON.parse for transform your "string from php" example:

var j = JSON.parse('[{"1": ["data1", "ENG"]},{ "2": ["data2","CHI"]}]'); 
    console.log(j);

check also this link:

Parse JSON in JavaScript?

Community
  • 1
  • 1
Rubén Fanjul Estrada
  • 1,296
  • 19
  • 31