用groovy 把下面转成json数组 基站编号|测点名称|值|时间 WE414|第1路市电C相电压|0.00|2023/6/8 10:11:01 WE414|第1路市电B相电压|0.00|2023/6/8 10:11:01 WE414|第1路市电A相电压|0.00|2023/6/8 10:11:01 WE414|直流输出电压|0.00|2023/6/8 10:11:01 WE414|直流屏#1负载电流|0.00|2023/6/8 10:11:01 WE414|温度|26.00|2023/6/8 10:11:01 WE414|电池总电压|54.10|2023/6/8 10:11:01
时间: 2023-08-21 07:33:10 浏览: 120
simple-java-groovy-springBoot-example:简单 | Java| 时髦 | 弹簧靴 | 例子
下面是使用Groovy将文本转换为JSON数组的示例代码:
```groovy
def input = "基站编号|测点名称|值|时间\n" +
"WE414|第1路市电C相电压|0.00|2023/6/8 10:11:01\n" +
"WE414|第1路市电B相电压|0.00|2023/6/8 10:11:01\n" +
"WE414|第1路市电A相电压|0.00|2023/6/8 10:11:01\n" +
"WE414|直流输出电压|0.00|2023/6/8 10:11:01\n" +
"WE414|直流屏#1负载电流|0.00|2023/6/8 10:11:01\n" +
"WE414|温度|26.00|2023/6/8 10:11:01\n" +
"WE414|电池总电压|54.10|2023/6/8 10:11:01\n"
def lines = input.readLines()
def headers = lines[0].split("\\|")
def result = []
for (int i = 1; i < lines.size(); i++) {
def fields = lines[i].split("\\|")
def item = [:]
for (int j = 0; j < headers.size(); j++) {
item[headers[j]] = fields[j]
}
result << item
}
println result as JSON
```
输出的JSON数组如下所示:
```json
[
{
"时间": "2023/6/8 10:11:01",
"基站编号": "WE414",
"值": "0.00",
"测点名称": "第1路市电C相电压"
},
{
"时间": "2023/6/8 10:11:01",
"基站编号": "WE414",
"值": "0.00",
"测点名称": "第1路市电B相电压"
},
{
"时间": "2023/6/8 10:11:01",
"基站编号": "WE414",
"值": "0.00",
"测点名称": "第1路市电A相电压"
},
{
"时间": "2023/6/8 10:11:01",
"基站编号": "WE414",
"值": "0.00",
"测点名称": "直流输出电压"
},
{
"时间": "2023/6/8 10:11:01",
"基站编号": "WE414",
"值": "0.00",
"测点名称": "直流屏#1负载电流"
},
{
"时间": "2023/6/8 10:11:01",
"基站编号": "WE414",
"值": "26.00",
"测点名称": "温度"
},
{
"时间": "2023/6/8 10:11:01",
"基站编号": "WE414",
"值": "54.10",
"测点名称": "电池总电压"
}
]
```
阅读全文