从textarea获取json文件

时间:2017-08-21 05:13:27

标签: javascript jquery html json

从textarea获取json文件,这个代码的位置错误,为何无法读取json

$(document).ready(function(){
$('textarea').change(function(){
        var fa=[ $('textarea').val() ];
    var sjson =[JSON.stringify(fa)];
    var tr;
    for (var i = 0; i < sjson.length; i++) {
        tr = $('<tr/>');
        tr.append('<td>' + sjson[i].day + '</td>');
        tr.append('<td>' + sjson[i].open + '</td>');
        tr.append('<td>' + sjson[i].close + '</td>');
        $('table').append(tr);
    }
});});

my fiddle

1 个答案:

答案 0 :(得分:1)

$(document).ready(function(){
$('textarea').change(function(){
        var fa="["+$('textarea').val()+"]";
    var sjson =jQuery.parseJSON(fa);
    var tr;
    $.each(sjson,function(key,value){
        tr = $('<tr/>');
        tr.append('<td>' + value.day + '</td>');
        tr.append('<td>' + value.open + '</td>');
        tr.append('<td>' + value.close + '</td>');
        $('table').append(tr)
    });
   
});});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>{
		"day": "sun",
		"open": "7:00",
		"close": "18:00"
	},
	{
		"day": "mon",
		"open": "8:00",
		"close": "18:00"
	}, {
		"day": "fri",
		"open": "9:00",
		"close": "17:00"
	}

</textarea>

<table></table>