必须登录才能发言。

  • 2
    @Ta 2024-04-29
    /

    @c,Golang是一种强类型、静态类型的编程语言,与Python不同,它的静态类型系统要求在编译时就确定变量的类型。不过,Golang也有很多优秀的 JSON 库可供选择,其中最知名的是 encoding/json 标准库。你可以使用它来解析和生成 JSON 数据。

    下面是一个简单的示例,演示了如何使用 encoding/json 标准库来解析 JSON 数据:

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    )
    
    // 定义一个结构体来表示 JSON 数据的结构
    type Book struct {
    	Title   string  `json:"title"`
    	Author  string  `json:"author"`
    	Price   float64 `json:"price"`
    	Category string  `json:"category"`
    }
    
    func main() {
    	// 示例 JSON 数据
    	jsonData := `[
    		{"title": "Sayings of the Century", "author": "Nigel Rees", "price": 8.95, "category": "reference"},
    		{"title": "Sword of Honour", "author": "Evelyn Waugh", "price": 12.99, "category": "fiction"},
    		{"title": "Moby Dick", "author": "Herman Melville", "price": 8.99, "category": "fiction"},
    		{"title": "The Lord of the Rings", "author": "J. R. R. Tolkien", "price": 22.99, "category": "fiction"}
    	]`
    
    	// 解析 JSON 数据
    	var books []Book
    	err := json.Unmarshal([]byte(jsonData), &books)
    	if err != nil {
    		fmt.Println("Error parsing JSON:", err)
    		return
    	}
    
    	// 打印解析后的数据
    	for _, book := range books {
    		fmt.Printf("Title: %s, Author: %s, Price: %.2f, Category: %s\n", book.Title, book.Author, book.Price, book.Category)
    	}
    }
    

    这个示例首先定义了一个 Book 结构体,用于表示 JSON 数据中的书籍信息。然后,使用 json.Unmarshal 函数将 JSON 数据解析到 books 变量中,最后打印出解析后的数据。

  • 1
    @Ta 2024-04-29
    /

    @c,你可以使用jsonpath库来执行表达式查询,它支持在JSON数据中进行灵活的查询操作。JSONPath是一种用于从JSON结构中提取数据的语言,类似于XPath用于XML文档。

    你可以通过以下方式安装jsonpath库:

    pip install jsonpath-ng
    

    然后,你可以使用它来执行查询操作,例如:

    import json
    from jsonpath_ng import jsonpath, parse
    
    # Example JSON data
    data = {
        "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
    }
    
    # Define your JSONPath expression
    expression = parse("$.store.book[*].author")
    
    # Execute the expression
    matches = expression.find(data)
    
    # Output the results
    for match in matches:
        print(match.value)
    

    这个例子中,我们使用JSONPath表达式$.store.book[*].author来查询所有书籍的作者。