在 Jayway JSONPath 中,stddev() 函数用来计算标准偏差。标准差(Standard Deviation)是一个用于描述数据集离散程度的统计量,它表示数据点相对于其平均值的平均偏差。
假设我们有以下 JSON 数据:
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}如果要计算所有书籍价格的标准差,可以使用 $..book[*].price.stddev() 表达式。
Java 示例:
package com.hxstrive.json_path.function;
import com.jayway.jsonpath.JsonPath;
/**
* stddev() 函数
* @author hxstrive.com
*/
public class FunctionDemo04 {
public static void main(String[] args) {
String json = "{" +
" \"store\": {" +
" \"book\": [" +
" {" +
" \"category\": \"reference\"," +
" \"author\": \"Nigel Rees\"," +
" \"title\": \"Sayings of the Century\"," +
" \"price\": 8.95" +
" }," +
" {" +
" \"category\": \"fiction\"," +
" \"author\": \"Evelyn Waugh\"," +
" \"title\": \"Sword of Honour\"," +
" \"price\": 12.99" +
" }," +
" {" +
" \"category\": \"fiction\"," +
" \"author\": \"Herman Melville\"," +
" \"title\": \"Moby Dick\"," +
" \"isbn\": \"0-553-21311-3\"," +
" \"price\": 8.99" +
" }," +
" {" +
" \"category\": \"fiction\"," +
" \"author\": \"J. R. R. Tolkien\"," +
" \"title\": \"The Lord of the Rings\"," +
" \"isbn\": \"0-395-19395-8\"," +
" \"price\": 22.99" +
" }" +
" ]," +
" \"bicycle\": {" +
" \"color\": \"red\"," +
" \"price\": 19.95" +
" }" +
" }," +
" \"expensive\": 10" +
"}";
Object obj = JsonPath.read(json, "$..book[*].price");
System.out.println(obj);
obj = JsonPath.read(json, "$..book[*].price.stddev()");
System.out.println(obj);
}
}运行示例,输出如下:
[8.95,12.99,8.99,22.99] 5.73064568787846