简体   繁体   English

如何将json数组转换为javascript数组

[英]how to convert json array to javascript array

I have below json array 我有json数组

`[{"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. 我想转换为javascript数组并打印为html。 then I would copy the array and save in .js file like below. 然后我会复制数组并保存在.js文件中,如下所示。 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: 如果你想打印这个数组,例如打印到<pre>容器,你可以使用JSON.stringify()和两个参数:

// 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. 好吧,我认为上面的json数组不是正确的JSON结构。 first we need to remove comma (,) from 120th index of your json array.. Now it will appear like this.. 首先我们需要从你的json数组的第120个索引中删除逗号(,)。现在它将显示为这样..

 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() 现在使用json.parse()

ie

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

hope this will help you.. 希望这个能对您有所帮助..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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