...

Source file src/github.com/clbanning/mxj/v2/examples/jpath.go

Documentation: github.com/clbanning/mxj/v2/examples

     1  // gitissue #28
     2  
     3  /*
     4  (reference: http://goessner.net/articles/JsonPath/)
     5  Let's practice JSONPath expressions by some more examples. We start with a simple JSON structure built after an XML example representing a bookstore (original XML file).
     6  
     7  { "store": {
     8      "book": [
     9        { "category": "reference",
    10          "author": "Nigel Rees",
    11          "title": "Sayings of the Century",
    12          "price": 8.95
    13        },
    14        { "category": "fiction",
    15          "author": "Evelyn Waugh",
    16          "title": "Sword of Honour",
    17          "price": 12.99
    18        },
    19        { "category": "fiction",
    20          "author": "Herman Melville",
    21          "title": "Moby Dick",
    22          "isbn": "0-553-21311-3",
    23          "price": 8.99
    24        },
    25        { "category": "fiction",
    26          "author": "J. R. R. Tolkien",
    27          "title": "The Lord of the Rings",
    28          "isbn": "0-395-19395-8",
    29          "price": 22.99
    30        }
    31      ],
    32      "bicycle": {
    33        "color": "red",
    34        "price": 19.95
    35      }
    36    }
    37  }
    38  XPath                JSONPath                 Result
    39  /store/book/author   $.store.book[*].author   the authors of all books in the store
    40  //author             $..author                all authors
    41  /store/*             $.store.*                all things in store, which are some books and a red bicycle.
    42  /store//price        $.store..price           the price of everything in the store.
    43  //book[3]            $..book[2]               the third book
    44  //book[last()]       $..book[(@.length-1)]
    45                       $..book[-1:]             the last book in order.
    46  //book[position()<3] $..book[0,1]
    47                       $..book[:2]              the first two books
    48  //book[isbn]         $..book[?(@.isbn)]       filter all books with isbn number
    49  //book[price<10]     $..book[?(@.price<10)]   filter all books cheapier than 10
    50  //*                  $..*                     all Elements in XML document. All members of JSON structure.
    51  
    52  */
    53  
    54  package main
    55  
    56  import (
    57  	"fmt"
    58  
    59  	"github.com/clbanning/mxj"
    60  )
    61  
    62  var data = []byte(`
    63  { "store": {
    64      "book": [ 
    65        { "category": "reference",
    66          "author": "Nigel Rees",
    67          "title": "Sayings of the Century",
    68          "price": 8.95
    69        },
    70        { "category": "fiction",
    71          "author": "Evelyn Waugh",
    72          "title": "Sword of Honour",
    73          "price": 12.99
    74        },
    75        { "category": "fiction",
    76          "author": "Herman Melville",
    77          "title": "Moby Dick",
    78          "isbn": "0-553-21311-3",
    79          "price": 8.99
    80        },
    81        { "category": "fiction",
    82          "author": "J. R. R. Tolkien",
    83          "title": "The Lord of the Rings",
    84          "isbn": "0-395-19395-8",
    85          "price": 22.99
    86        }
    87      ],
    88      "bicycle": {
    89        "color": "red",
    90        "price": 19.95
    91      }
    92    }
    93  }`)
    94  
    95  func main() {
    96  	m, err := mxj.NewMapJson(data)
    97  	if err != nil {
    98  		fmt.Println("NewMapJson err:", err)
    99  		return
   100  	}
   101  
   102  	// $.store.book[*].author   the authors of all books in the store
   103  	list, err := m.ValuesForPath("store.book.author")
   104  	if err != nil {
   105  		fmt.Println("book author err:", err)
   106  		return
   107  	}
   108  	fmt.Println("authors:", list)
   109  
   110  	// $..author                all authors
   111  	list, err = m.ValuesForKey("author")
   112  	if err != nil {
   113  		fmt.Println("author err:", err)
   114  		return
   115  	}
   116  	fmt.Println("authors:", list)
   117  
   118  	// $.store.*                all things in store, which are some books and a red bicycle.
   119  	list, err = m.ValuesForKey("store")
   120  	if err != nil {
   121  		fmt.Println("store things err:", err)
   122  	}
   123  	fmt.Println("store things:", list)
   124  
   125  	// /store//price        $.store..price           the price of everything in the store.
   126  	list, err = m.ValuesForKey("price")
   127  	if err != nil {
   128  		fmt.Println("price of things err:", err)
   129  	}
   130  	fmt.Println("price of things:", list)
   131  
   132  	// $..book[2]               the third book
   133  	v, err := m.ValueForPath("store.book[2]")
   134  	if err != nil {
   135  		fmt.Println("price of things err:", err)
   136  	}
   137  	fmt.Println("3rd book:", v)
   138  
   139  	// $..book[-1:]             the last book in order
   140  	list, err = m.ValuesForPath("store.book")
   141  	if err != nil {
   142  		fmt.Println("list of books err:", err)
   143  	}
   144  	if len(list) <= 1 {
   145  		fmt.Println("last book:", list)
   146  	} else {
   147  		fmt.Println("last book:", list[len(list)-1:])
   148  	}
   149  
   150  	// $..book[:2]              the first two books
   151  	list, err = m.ValuesForPath("store.book")
   152  	if err != nil {
   153  		fmt.Println("list of books err:", err)
   154  	}
   155  	if len(list) <= 2 {
   156  		fmt.Println("1st 2 books:", list)
   157  	} else {
   158  		fmt.Println("1st 2 books:", list[:2])
   159  	}
   160  
   161  	// $..book[?(@.isbn)]       filter all books with isbn number
   162  	list, err = m.ValuesForPath("store.book", "isbn:*")
   163  	if err != nil {
   164  		fmt.Println("list of books err:", err)
   165  	}
   166  	fmt.Println("books with isbn:", list)
   167  
   168  	// $..book[?(@.price<10)]   filter all books cheapier than 10
   169  	list, err = m.ValuesForPath("store.book")
   170  	if err != nil {
   171  		fmt.Println("list of books err:", err)
   172  	}
   173  	var n int
   174  	for _, v := range list {
   175  		if v.(map[string]interface{})["price"].(float64) >= 10.0 {
   176  			continue
   177  		}
   178  		list[n] = v
   179  		n++
   180  	}
   181  	list = list[:n]
   182  	fmt.Println("books with price < $10:", list)
   183  
   184  	// $..*                     all Elements in XML document. All members of JSON structure.
   185  	// 1st where values are not complex elements
   186  	list = m.LeafValues()
   187  	fmt.Println("list of leaf values:", list)
   188  
   189  	// $..*                     all Elements in XML document. All members of JSON structure.
   190  	// 2nd every value - even complex elements
   191  	path := "*"
   192  	list = make([]interface{}, 0)
   193  	for {
   194  		v, _ := m.ValuesForPath(path)
   195  		if len(v) == 0 {
   196  			break
   197  		}
   198  		list = append(list, v...)
   199  		path = path + ".*"
   200  	}
   201  	fmt.Println("list of all values:", list)
   202  }
   203  

View as plain text