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
-
possible duplicate of Access / process (nested) objects, arrays or JSONFelix Kling– Felix Kling2014年03月31日 15:21:59 +00:00Commented Mar 31, 2014 at 15:21
-
stackoverflow.com/questions/4935632/…pj013– pj0132014年03月31日 15:23:47 +00:00Commented Mar 31, 2014 at 15:23
3 Answers 3
Use:
var data = JSON.parse(ArrayHere);
console.log(data);
data.something = "hello";
And back is
var JSON = JSON.stringify(data);
Comments
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
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: