Golang如何从JSON对象中提取数据并展示在表格中
Golang如何从JSON对象中提取数据并展示在表格中
import React from "react";
import { Button, Form, FormGroup, Label, Input, FormText,Row } from 'reactstrap';
import Icon from 'react-icons-kit';
import {filter} from "react-icons-kit/fa/filter";
import { pencil,bin,search } from 'react-icons-kit/icomoon';
import { ic_delete, ic_create } from 'react-icons-kit/md';
import {Link} from "react-router-dom";
import {activeStyle} from "../projects/Projects.css";
import {orange,contentStyle,displayContainer,pageHeading,hrStyle,buttonStyle,floatRight1,exampletable,savebtn1,bankdiv,btnstyle} from "../Layout.css";
import {hyperLink} from "../settings/LayoutSettings.css";
import {Header} from "../Header";
import {Footer} from "../Footer";
import $ from 'jquery';
var result = [];
var URL = 'http://localhost:3033/';
var parsed="";
function searchingFor(term){
return function(x){
return x.ID.toLowerCase().includes(term.toLowerCase()) || x.ExpenseName.toLowerCase().includes(term.toLowerCase()) ;
}
}
export class ClaimList extends React.Component{
constructor(){
super()
this.state = {
//data: []
term: '',
result: []
};
this.searchHandler = this.searchHandler.bind(this)
}
searchHandler(event){
this.setState({
term: event.target.value
})
}
componentDidMount(){
this.Claimlist();
}
Claimlist(){
//alert("called")
$.ajax({
url: URL + '/ClaimList',
type: "GET",
dataType: 'json',
ContentType: 'application/json',
success: function(parsed) {
parsed = JSON.stringify(parsed);
console.log(parsed)
var vals = Object.values(parsed);
// for(var x in parsed){
// result.push(parsed[x]);
// }
//result = $.parseJSON(parsed);
//data = JSON.stringify(data);
this.setState(vals);
console.log(vals)
}.bind(this),
error: function(jqXHR) {
console.log(jqXHR);
}.bind(this)
})
}//$.ajax({
// url: URL + '/ClaimList',
// type: 'GET',
// cache: false,
// success: function (ClaimResult) {
// ClaimResult = JSON.parse(ClaimResult);
// //console.log(ClaimResult)
// this.setState({ClaimResult:ClaimResult});
// if (ClaimResult.Status === 'true') {
// result=Json.parse(Json.stringify(ClaimResult))
// // ClaimResult.Message.map(r =>{
// // result.push(r)
// }
// // result.map(r =>{
// // // console.log(r.ID)
// // })
// else {
// alert(result);
// }
// },
// error: function () {
// alert('Unable to update job details !!!');
// },
// complete: function () {
// alert()
// }
// });
// MyTableGrid(){
// render: {
// return (
// result.map(r =>
// //<li key={post.id}>{post.title}</li>
// <tr key ={r.ID}>
// <td>{r.ID}</td>
// <td>{r.ExpenseName}</td>
// <td>{r.Amount}</td>
// <td>{r.Date}</td>
// <td>{r.Description}</td>
// <td className={activeStyle}></td>
// <td> <Link to="/AddExpenses" className={hyperLink}><Icon icon={ic_create} size={20}/></Link>
// <Icon icon={ic_delete} style={{marginLeft:'1vw'}} size={20} /> </td>
// </tr>
// )
// )
// }
// }
// renderProducts() {
// this.state.result.map(product => {
// return (
// <tr>
// <td>{product.ID}</td>
// <td>{product.ExpenseName}</td>
// <td>{product.Amount}</td>
// </tr>
// );
// })
// }
render(){
return(
<div>
{/* <table>
<tbody>
{this.state.result.map(function(item, key) {
return (
<tr key = {key.id}>
<td>{item.ID}</td>
<td>{item.ExpenseName}</td>
<td>{item.Amount}</td>
<td>{item.Description}</td>
</tr>
)
})}
</tbody>
</table> */}
<Header/>
<div className={displayContainer}>
<p className={pageHeading}>Claims</p>
<hr className={hrStyle}/>
<span className={floatRight1}>
<form class="form-row" method="GET" >
<input type="search" placeholder="Search" onChange={this.searchHandler} />
<div class="dropdown" style={{position:'relative',left:'-1vw'}} >
<button class="btn btn-outline-light" type="button" id={btnstyle} data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<Icon icon={filter} />
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item">Employee ID</a>
<a class="dropdown-item">Expense Title</a>
<a class="dropdown-item">Date</a>
<a class="dropdown-item">Amount</a>
</div>
</div>
</form>
</span>
<table class="table table-bordered table-striped table-responsive-md" >
<thead>
<tr className={orange}>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Expense Title</th>
<th>Description</th>
<th>Amount</th>
<th>Date</th>
<th>Actions</th>
</tr>
{
this.state.result.filter(searchingFor(this.state.term)).map(function(key){
return (
<tr key={key}>
<td>{person.ID}</td>
<td> {person.EmployeeName} </td>
<td>{person.ExpenseName}</td>
<td> {person.Description} </td>
<td> {person.Amount} </td>
<td> {person.Date} </td>
</tr>
)
})
}
</thead>
<tbody>
{/* {this.MyTableGrid()} */}
{/* {this.renderProducts()} */}
</tbody>
</table>
<div className={bankdiv} style={{marginTop:'7vw',marginLeft:'-7.7vw'}}>
<Link to="/AddClaims"><button className="btn btn-outline-warning" >
Add New Claim</button></Link>
</div>
</div>
<Footer/>
</div>
);
}
}
更多关于Golang如何从JSON对象中提取数据并展示在表格中的实战教程也可以访问 https://www.itying.com/category-94-b0.html
4 回复
你可能应该用 Go 语言重写这段代码,以便在这里获得适当的审查。
这是在ReactJS中实现的…我正在从Go页面获取数据并转换为JSON…现在我需要将这些JSON数据展示在表格中
在Go语言中,从JSON对象提取数据并展示在表格中,通常使用标准库的encoding/json包进行JSON解析,并结合HTML模板或第三方库(如github.com/olekukonko/tablewriter)来生成表格。以下是一个完整的示例,展示如何解析JSON数据并将其输出为表格格式。
首先,假设我们有以下JSON数据,表示多个报销申请记录:
[
{
"ID": "1",
"EmployeeName": "张三",
"ExpenseName": "差旅费",
"Description": "北京出差交通费用",
"Amount": 500.00,
"Date": "2023-10-01"
},
{
"ID": "2",
"EmployeeName": "李四",
"ExpenseName": "办公用品",
"Description": "购买打印纸和笔",
"Amount": 200.50,
"Date": "2023-10-02"
}
]
在Go中,我们可以定义一个结构体来映射JSON数据,然后使用json.Unmarshal解析JSON,并使用tablewriter库生成表格输出。
步骤1:安装tablewriter库(如果尚未安装)
在终端中运行:
go get github.com/olekukonko/tablewriter
步骤2:编写Go代码
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/olekukonko/tablewriter"
)
// 定义结构体以映射JSON字段
type Claim struct {
ID string `json:"ID"`
EmployeeName string `json:"EmployeeName"`
ExpenseName string `json:"ExpenseName"`
Description string `json:"Description"`
Amount float64 `json:"Amount"`
Date string `json:"Date"`
}
func main() {
// 示例JSON数据(在实际应用中,可能来自文件或HTTP响应)
jsonData := `[
{
"ID": "1",
"EmployeeName": "张三",
"ExpenseName": "差旅费",
"Description": "北京出差交通费用",
"Amount": 500.00,
"Date": "2023-10-01"
},
{
"ID": "2",
"EmployeeName": "李四",
"ExpenseName": "办公用品",
"Description": "购买打印纸和笔",
"Amount": 200.50,
"Date": "2023-10-02"
}
]`
// 解析JSON数据到Claim结构体切片
var claims []Claim
err := json.Unmarshal([]byte(jsonData), &claims)
if err != nil {
log.Fatalf("解析JSON失败: %v", err)
}
// 创建表格写入器,输出到标准输出
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"员工ID", "员工姓名", "费用标题", "描述", "金额", "日期"})
// 遍历claims切片,添加每一行数据到表格
for _, claim := range claims {
row := []string{
claim.ID,
claim.EmployeeName,
claim.ExpenseName,
claim.Description,
fmt.Sprintf("%.2f", claim.Amount),
claim.Date,
}
table.Append(row)
}
// 渲染表格
table.Render()
}
步骤3:运行代码
执行上述Go程序,输出将是一个格式化的表格:
+--------+------------+------------+----------------------+--------+------------+
| 员工ID | 员工姓名 | 费用标题 | 描述 | 金额 | 日期 |
+--------+------------+------------+----------------------+--------+------------+
| 1 | 张三 | 差旅费 | 北京出差交通费用 | 500.00 | 2023-10-01 |
| 2 | 李四 | 办公用品 | 购买打印纸和笔 | 200.50 | 2023-10-02 |
+--------+------------+------------+----------------------+--------+------------+
说明:
- JSON解析:使用
encoding/json包将JSON数据解码到Go结构体切片中。 - 表格生成:利用
tablewriter库创建表格,设置表头并逐行添加数据。 - 错误处理:在解析JSON时检查错误,确保数据格式正确。
如果JSON数据来自HTTP响应(如从API获取),可以使用http.Get获取数据,然后解析。例如:
resp, err := http.Get("http://localhost:3033/ClaimList")
if err != nil {
log.Fatalf("HTTP请求失败: %v", err)
}
defer resp.Body.Close()
var claims []Claim
err = json.NewDecoder(resp.Body).Decode(&claims)
if err != nil {
log.Fatalf("解析响应JSON失败: %v", err)
}
// 然后使用tablewriter生成表格
此方法适用于在命令行或控制台中展示表格数据。如果需要在Web页面中显示,可以结合HTML模板(如html/template包)生成HTML表格。


