我正在尝试解析Laravel应用程序提供给我的Vue视图的JSON字符串。 JSON字符串如下所示:
{
"1":[ { "row":"Some text here on first column." },
{ "row":"And more text. Second row." },
{ "row":"Text!" }
],
"2":[ { "row":"2nd column text." },
{ "row":"" }
],
"3":[ { "row":"Even more text. But on the third column." }
]
}
这里要注意的事情:
我正在尝试将字符串解析为表格,例如:https://jsfiddle.net/59bz2hqs/1/
这就是我现在拥有的:
<template>
<div>
<table>
<tbody>
<tr v-for="row in this.content">
<td>{{row}}</td>
</tr>
</tbody>
</table>
<div>
</template>
<script>
export default {
data() {
return {
content: []
}
},
created() {
Event.$on("document-was-processed", content => {
this.content = content;
});
}
}
</script>
现在,上面仅打印出实际的JSON字符串。谁能帮助我解决如何实际解析内容?
对此有更多思考。我实际上不确定我的JSON字符串布局是否还可以支持所需的输出。
也许像下面的东西?不太确定。
{ "1":[
{ "text":"Some text here on first column."},
{ "text":"2nd column text."},
{ "text":"Even more text. But on the third column"}
],
"2":[
{ "text":"And more text. Second row." },
{ "text":"" },
{ "text":"" }
],
"3":[
{ "text":"Text!"},
{ "text":""},
{ "text":""}
]}
然后类似:
<table class="text-left w-full border-collapse m-3">
<thead>
<tr class="bg-gray-100">
<th v-for="(item, idx) in this.content" class="p-1">
{{idx}}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rid) in this.content">
<td v-for="(col, cid) in row">{{ col.text }} </td>
</tr>
</tbody>
</table>
答案 0 :(得分:2)
在呈现数据之前,您必须transpose数据。
这是我的伪代码
<script>
export default {
data() {
return {
dataTable: []
};
},
created() {
// Instead of fetching your content I put it in a local variable
let content = JSON.parse(`{
"1":[ { "row":"Some text here on first column." },
{ "row":"And more text. Second row." },
{ "row":"Text!" }
],
"2":[ { "row":"2nd column text." },
{ "row":"" }
],
"3":[ { "row":"Even more text. But on the third column." }
]
}`);
// Transform object in array of its values
let data = Object.values(content);
let colsLength = data.map(r => r.length);
let maxNumCols = Math.max.apply(Math, colsLength);
let colsArraySchema = Array.apply(null, Array(maxNumCols)).map((r, i) => i);
this.dataTable = colsArraySchema.map((col, i) => data.map(row => row[i]));
// For debug.
console.log(content);
console.log(data);
console.log(colsLength);
console.log(maxNumCols);
console.log(this.dataTable);
}
};
</script>
现在,您可以在模板中呈现dataTable变量。 (请注意,行数组可能包含未定义的值)
<template>
<table border="1">
<tbody>
<tr v-for="(row, index) in dataTable" :key="index">
<td v-for="(cell, index) in row" :key="index">
<span v-if="cell">{{cell["row"]}}</span>
</td>
</tr>
</tbody>
</table>
</template>
您可以在此处观看实时演示:https://codesandbox.io/s/vue-json-transpose-dt915
希望对您有帮助。