所以,如果我知道将在json中获得什么类型的数据,我清楚地了解如何将JSON转换为HTML。
但是,如果我不知道从服务器获得什么样的密钥,我怎么能使用json2html?
这里的代码可以正确使用静态密钥:
<button [routerLink]="['compliance', {outlets: { primary: 'ComplianceTableComponent', topbar: 'complianceBar'}}]">test</button>
&#13;
var data = {'json': [{
'order': 'By',
'name': 'Stack',
'randomkey': '3',
'randomkey_n': '0',
'score': '121',
'id': '540'
}]};
var transform = {
tag: 'tr',
children: [{
"tag": "td",
"html": "${order}"
}, {
"tag": "td",
"html": "${name}"
}, {
"tag": "td",
"html": "${randomkey}"
}, {
"tag": "td",
"html": "${randomkey_n}"
}, {
"tag": "td",
"html": "${score}"
}]
};
$('#placar > tbody ').json2html(data.json, transform);
&#13;
我明白,我应该在<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://json2html.com/js/json2html.js"></script>
<script src="http://json2html.com/js/jquery.json2html.js"></script>
<div class="container">
<p>
<table id="placar" class="table table-condensed table-bordered">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
中使用内联函数,但我无法理解如何返回&#34; random&#34;密钥。
答案 0 :(得分:1)
您可以使用private async void MarkdownText_LinkClicked(object sender, UI.Controls.LinkClickedEventArgs e)
{
await Launcher.LaunchUriAsync(new Uri(e.Link));
}
列出属性,使用Object.keys
排除id
属性(因为您似乎不会渲染它),最后将.filter()
属性排除到对象结构您需要.map()
属性:
children
&#13;
var data = {'json': [{
'order': 'By',
'name': 'Stack',
'randomkey': '3',
'randomkey_n': '0',
'score': '121',
'id': '540'
}]};
var transform = {
tag: 'tr',
children: Object.keys(data.json[0]) // get keys
.filter(key => key !== 'id') // exclude id
.map(key => ({ // convert to object for transformation
"tag": "td",
"html": "${" + key + "}"
}))
};
$('#placar > tbody ').json2html(data.json, transform);
&#13;
如果您有其他属性应该被排除,例如 id ,那么您可以这样做:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://json2html.com/js/json2html.js"></script>
<script src="http://json2html.com/js/jquery.json2html.js"></script>
<div class="container">
<p>
<table id="placar" class="table table-condensed table-bordered">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
或者,如果你有很多这样的属性,首先定义一个集合来提高效率:
.filter(key => !['id', 'otherfield', 'comment'].includes(key))
...然后过滤变为:
const excludes = new Set(['id', 'otherfield', 'comment', /* many others...*/]);
答案 1 :(得分:0)
很好的回答tincot ..只是为了添加另一种方法,这可能会更容易理解。您可以将json对象转换为具有属性名称和值的数组,然后使用静态转换
var data = {'json': [{
'order': 'By',
'name': 'Stack',
'randomkey': '3',
'randomkey_n': '0',
'score': '121',
'id': '540'
}]};
var transform = {"<>": "tr","html":[
{"<>":"td","html":"${val}"}
]};
var _data = [];
for(var i=0; i < data.json.length; i++){
var out = [];
for(var prop in data.json[i])
if(prop !== "id") out[i] = {"name":prop,"val":data.json[i][prop]};
_data.push(out);
}
$('#placar > tbody ').json2html(_data, transform);