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

2

3 Answers 3

2

Use:

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

And back is

var JSON = JSON.stringify(data);
Sign up to request clarification or add additional context in comments.

Comments

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",

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.