简体   繁体   中英

how to convert json array to javascript array

I have below json array

`[{"name":"The Shawshank Redemption","rating":"9.3","year":"1994","stars":["Tim Robbins","Morgan Freeman","Bob Gunton"],},{"name":"The Godfather","rating":"9.2","year":"1972","stars":["Marlon Brando","Al Pacino","James Caan"]}]`

I want to convert in javascript array and print as html. then I would copy the array and save in .js file like below. problem is how to remove the inverted coma from "name" to name

var Movies =  [ { name: 'The Shawshank Redemption',
rating: '9.3',
year: '1994',
stars:
 [ 'Tim Robbins',
   'Morgan Freeman',
   'Bob Gunton' ]},
{ name: 'The Godfather',
rating: '9.2',
year: '1972',
stars:
 [ 'Marlon Brando',
   'Al Pacino',
   'James Caan' ]}
];
var movies= $.parseJSON(myStr); put your string in it

for printing

var newAry=[];
$.each(movies,function(i,v){
  newAry.push(JSON.stringify(v));
});

$( '#div' ).html(newAry);

If you want to pretty print this array, eg into a <pre> container, you could use JSON.stringify() with both parameters:

// assuming your parsed JSON is in this variable
var yourObj = JSON.parse( "[your JSON in here]" );

// pretty print
var pretty = JSON.stringify( yourObj, null, '  ' );
document.getElementById( 'target' ).innerHTML = pretty;

do you mean :

var a = [];
a.push($.parseJSON('{"a":"b"}'));

?

well, I think above json array is not in proper JSON structure. first we need to remove comma (,) from 120th index of your json array.. Now it will appear like this..

 var jsonArray = `[{"name":"The Shawshank Redemption","rating":"9.3","year":"1994","stars":["Tim Robbins","Morgan Freeman","Bob Gunton"]},{"name":"The Godfather","rating":"9.2","year":"1972","stars":["Marlon Brando","Al Pacino","James Caan"]}]` ;

now use json.parse()

ie

var Movies = JSON && JSON.parse(jsonArray);

hope this will help you..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM