How to use JSONPointer method of td Package

Best Go-testdeep code snippet using td.JSONPointer

example_test.go

Source:example_test.go Github

copy

Full Screen

...783 td.Smuggle("Age", td.Gt(30)),784 td.Smuggle("Fullname", "Bob Foobar")))785 fmt.Println("first person.Age > 30 → Bob:", ok)786 ok = td.Cmp(t, got, td.First(787 td.JSONPointer("/age", td.Gt(30)),788 td.SuperJSONOf(`{"fullname":"Bob Foobar"}`)))789 fmt.Println("first person.Age > 30 → Bob, using JSON:", ok)790 ok = td.Cmp(t, got, td.First(791 td.JSONPointer("/age", td.Gt(30)),792 td.JSONPointer("/fullname", td.HasPrefix("Bob"))))793 fmt.Println("first person.Age > 30 → Bob, using JSONPointer:", ok)794 // Output:795 // first person.Age > 30 → Bob: true796 // first person.Age > 30 → Bob, using JSON: true797 // first person.Age > 30 → Bob, using JSONPointer: true798}799func ExampleFirst_json() {800 t := &testing.T{}801 got := map[string]any{802 "values": []int{1, 2, 3, 4},803 }804 ok := td.Cmp(t, got, td.JSON(`{"values": First(Gt(2), 3)}`))805 fmt.Println("first number > 2:", ok)806 got = map[string]any{807 "persons": []map[string]any{808 {"id": 1, "name": "Joe"},809 {"id": 2, "name": "Bob"},810 {"id": 3, "name": "Alice"},811 {"id": 4, "name": "Brian"},812 {"id": 5, "name": "Britt"},813 },814 }815 ok = td.Cmp(t, got, td.JSON(`816{817 "persons": First(JSONPointer("/name", "Brian"), {"id": 4, "name": "Brian"})818}`))819 fmt.Println(`is "Brian" content OK:`, ok)820 ok = td.Cmp(t, got, td.JSON(`821{822 "persons": First(JSONPointer("/name", "Brian"), JSONPointer("/id", 4))823}`))824 fmt.Println(`ID of "Brian" is 4:`, ok)825 // Output:826 // first number > 2: true827 // is "Brian" content OK: true828 // ID of "Brian" is 4: true829}830func ExampleGrep_classic() {831 t := &testing.T{}832 got := []int{-3, -2, -1, 0, 1, 2, 3}833 ok := td.Cmp(t, got, td.Grep(td.Gt(0), []int{1, 2, 3}))834 fmt.Println("check positive numbers:", ok)835 isEven := func(x int) bool { return x%2 == 0 }836 ok = td.Cmp(t, got, td.Grep(isEven, []int{-2, 0, 2}))837 fmt.Println("even numbers are -2, 0 and 2:", ok)838 ok = td.Cmp(t, got, td.Grep(isEven, td.Set(0, 2, -2)))839 fmt.Println("even numbers are also 0, 2 and -2:", ok)840 ok = td.Cmp(t, got, td.Grep(isEven, td.ArrayEach(td.Code(isEven))))841 fmt.Println("even numbers are each even:", ok)842 // Output:843 // check positive numbers: true844 // even numbers are -2, 0 and 2: true845 // even numbers are also 0, 2 and -2: true846 // even numbers are each even: true847}848func ExampleGrep_nil() {849 t := &testing.T{}850 var got []int851 ok := td.Cmp(t, got, td.Grep(td.Gt(0), ([]int)(nil)))852 fmt.Println("typed []int nil:", ok)853 ok = td.Cmp(t, got, td.Grep(td.Gt(0), ([]string)(nil)))854 fmt.Println("typed []string nil:", ok)855 ok = td.Cmp(t, got, td.Grep(td.Gt(0), td.Nil()))856 fmt.Println("td.Nil:", ok)857 ok = td.Cmp(t, got, td.Grep(td.Gt(0), []int{}))858 fmt.Println("empty non-nil slice:", ok)859 // Output:860 // typed []int nil: true861 // typed []string nil: false862 // td.Nil: true863 // empty non-nil slice: false864}865func ExampleGrep_struct() {866 t := &testing.T{}867 type Person struct {868 Fullname string `json:"fullname"`869 Age int `json:"age"`870 }871 got := []*Person{872 {873 Fullname: "Bob Foobar",874 Age: 42,875 },876 {877 Fullname: "Alice Bingo",878 Age: 27,879 },880 }881 ok := td.Cmp(t, got, td.Grep(882 td.Smuggle("Age", td.Gt(30)),883 td.All(884 td.Len(1),885 td.ArrayEach(td.Smuggle("Fullname", "Bob Foobar")),886 )))887 fmt.Println("person.Age > 30 → only Bob:", ok)888 ok = td.Cmp(t, got, td.Grep(889 td.JSONPointer("/age", td.Gt(30)),890 td.JSON(`[ SuperMapOf({"fullname":"Bob Foobar"}) ]`)))891 fmt.Println("person.Age > 30 → only Bob, using JSON:", ok)892 // Output:893 // person.Age > 30 → only Bob: true894 // person.Age > 30 → only Bob, using JSON: true895}896func ExampleGrep_json() {897 t := &testing.T{}898 got := map[string]any{899 "values": []int{1, 2, 3, 4},900 }901 ok := td.Cmp(t, got, td.JSON(`{"values": Grep(Gt(2), [3, 4])}`))902 fmt.Println("grep a number > 2:", ok)903 got = map[string]any{904 "persons": []map[string]any{905 {"id": 1, "name": "Joe"},906 {"id": 2, "name": "Bob"},907 {"id": 3, "name": "Alice"},908 {"id": 4, "name": "Brian"},909 {"id": 5, "name": "Britt"},910 },911 }912 ok = td.Cmp(t, got, td.JSON(`913{914 "persons": Grep(JSONPointer("/name", HasPrefix("Br")), [915 {"id": 4, "name": "Brian"},916 {"id": 5, "name": "Britt"},917 ])918}`))919 fmt.Println(`grep "Br" prefix:`, ok)920 // Output:921 // grep a number > 2: true922 // grep "Br" prefix: true923}924func ExampleGt_int() {925 t := &testing.T{}926 got := 156927 ok := td.Cmp(t, got, td.Gt(155), "checks %v is > 155", got)928 fmt.Println(ok)929 ok = td.Cmp(t, got, td.Gt(156), "checks %v is > 156", got)930 fmt.Println(ok)931 // Output:932 // true933 // false934}935func ExampleGt_string() {936 t := &testing.T{}937 got := "abc"938 ok := td.Cmp(t, got, td.Gt("abb"), `checks "%v" is > "abb"`, got)939 fmt.Println(ok)940 ok = td.Cmp(t, got, td.Gt("abc"), `checks "%v" is > "abc"`, got)941 fmt.Println(ok)942 // Output:943 // true944 // false945}946func ExampleGte_int() {947 t := &testing.T{}948 got := 156949 ok := td.Cmp(t, got, td.Gte(156), "checks %v is ≥ 156", got)950 fmt.Println(ok)951 ok = td.Cmp(t, got, td.Gte(155), "checks %v is ≥ 155", got)952 fmt.Println(ok)953 ok = td.Cmp(t, got, td.Gte(157), "checks %v is ≥ 157", got)954 fmt.Println(ok)955 // Output:956 // true957 // true958 // false959}960func ExampleGte_string() {961 t := &testing.T{}962 got := "abc"963 ok := td.Cmp(t, got, td.Gte("abc"), `checks "%v" is ≥ "abc"`, got)964 fmt.Println(ok)965 ok = td.Cmp(t, got, td.Gte("abb"), `checks "%v" is ≥ "abb"`, got)966 fmt.Println(ok)967 ok = td.Cmp(t, got, td.Gte("abd"), `checks "%v" is ≥ "abd"`, got)968 fmt.Println(ok)969 // Output:970 // true971 // true972 // false973}974func ExampleIsa() {975 t := &testing.T{}976 type TstStruct struct {977 Field int978 }979 got := TstStruct{Field: 1}980 ok := td.Cmp(t, got, td.Isa(TstStruct{}), "checks got is a TstStruct")981 fmt.Println(ok)982 ok = td.Cmp(t, got, td.Isa(&TstStruct{}),983 "checks got is a pointer on a TstStruct")984 fmt.Println(ok)985 ok = td.Cmp(t, &got, td.Isa(&TstStruct{}),986 "checks &got is a pointer on a TstStruct")987 fmt.Println(ok)988 // Output:989 // true990 // false991 // true992}993func ExampleIsa_interface() {994 t := &testing.T{}995 got := bytes.NewBufferString("foobar")996 ok := td.Cmp(t, got, td.Isa((*fmt.Stringer)(nil)),997 "checks got implements fmt.Stringer interface")998 fmt.Println(ok)999 errGot := fmt.Errorf("An error #%d occurred", 123)1000 ok = td.Cmp(t, errGot, td.Isa((*error)(nil)),1001 "checks errGot is a *error or implements error interface")1002 fmt.Println(ok)1003 // As nil, is passed below, it is not an interface but nil… So it1004 // does not match1005 errGot = nil1006 ok = td.Cmp(t, errGot, td.Isa((*error)(nil)),1007 "checks errGot is a *error or implements error interface")1008 fmt.Println(ok)1009 // BUT if its address is passed, now it is OK as the types match1010 ok = td.Cmp(t, &errGot, td.Isa((*error)(nil)),1011 "checks &errGot is a *error or implements error interface")1012 fmt.Println(ok)1013 // Output:1014 // true1015 // true1016 // false1017 // true1018}1019func ExampleJSON_basic() {1020 t := &testing.T{}1021 got := &struct {1022 Fullname string `json:"fullname"`1023 Age int `json:"age"`1024 }{1025 Fullname: "Bob",1026 Age: 42,1027 }1028 ok := td.Cmp(t, got, td.JSON(`{"age":42,"fullname":"Bob"}`))1029 fmt.Println("check got with age then fullname:", ok)1030 ok = td.Cmp(t, got, td.JSON(`{"fullname":"Bob","age":42}`))1031 fmt.Println("check got with fullname then age:", ok)1032 ok = td.Cmp(t, got, td.JSON(`1033// This should be the JSON representation of a struct1034{1035 // A person:1036 "fullname": "Bob", // The name of this person1037 "age": 42 /* The age of this person:1038 - 42 of course1039 - to demonstrate a multi-lines comment */1040}`))1041 fmt.Println("check got with nicely formatted and commented JSON:", ok)1042 ok = td.Cmp(t, got, td.JSON(`{"fullname":"Bob","age":42,"gender":"male"}`))1043 fmt.Println("check got with gender field:", ok)1044 ok = td.Cmp(t, got, td.JSON(`{"fullname":"Bob"}`))1045 fmt.Println("check got with fullname only:", ok)1046 ok = td.Cmp(t, true, td.JSON(`true`))1047 fmt.Println("check boolean got is true:", ok)1048 ok = td.Cmp(t, 42, td.JSON(`42`))1049 fmt.Println("check numeric got is 42:", ok)1050 got = nil1051 ok = td.Cmp(t, got, td.JSON(`null`))1052 fmt.Println("check nil got is null:", ok)1053 // Output:1054 // check got with age then fullname: true1055 // check got with fullname then age: true1056 // check got with nicely formatted and commented JSON: true1057 // check got with gender field: false1058 // check got with fullname only: false1059 // check boolean got is true: true1060 // check numeric got is 42: true1061 // check nil got is null: true1062}1063func ExampleJSON_placeholders() {1064 t := &testing.T{}1065 type Person struct {1066 Fullname string `json:"fullname"`1067 Age int `json:"age"`1068 Children []*Person `json:"children,omitempty"`1069 }1070 got := &Person{1071 Fullname: "Bob Foobar",1072 Age: 42,1073 }1074 ok := td.Cmp(t, got, td.JSON(`{"age": $1, "fullname": $2}`, 42, "Bob Foobar"))1075 fmt.Println("check got with numeric placeholders without operators:", ok)1076 ok = td.Cmp(t, got,1077 td.JSON(`{"age": $1, "fullname": $2}`,1078 td.Between(40, 45),1079 td.HasSuffix("Foobar")))1080 fmt.Println("check got with numeric placeholders:", ok)1081 ok = td.Cmp(t, got,1082 td.JSON(`{"age": "$1", "fullname": "$2"}`,1083 td.Between(40, 45),1084 td.HasSuffix("Foobar")))1085 fmt.Println("check got with double-quoted numeric placeholders:", ok)1086 ok = td.Cmp(t, got,1087 td.JSON(`{"age": $age, "fullname": $name}`,1088 td.Tag("age", td.Between(40, 45)),1089 td.Tag("name", td.HasSuffix("Foobar"))))1090 fmt.Println("check got with named placeholders:", ok)1091 got.Children = []*Person{1092 {Fullname: "Alice", Age: 28},1093 {Fullname: "Brian", Age: 22},1094 }1095 ok = td.Cmp(t, got,1096 td.JSON(`{"age": $age, "fullname": $name, "children": $children}`,1097 td.Tag("age", td.Between(40, 45)),1098 td.Tag("name", td.HasSuffix("Foobar")),1099 td.Tag("children", td.Bag(1100 &Person{Fullname: "Brian", Age: 22},1101 &Person{Fullname: "Alice", Age: 28},1102 ))))1103 fmt.Println("check got w/named placeholders, and children w/go structs:", ok)1104 ok = td.Cmp(t, got,1105 td.JSON(`{"age": Between($1, $2), "fullname": HasSuffix($suffix), "children": Len(2)}`,1106 40, 45,1107 td.Tag("suffix", "Foobar")))1108 fmt.Println("check got w/num & named placeholders:", ok)1109 // Output:1110 // check got with numeric placeholders without operators: true1111 // check got with numeric placeholders: true1112 // check got with double-quoted numeric placeholders: true1113 // check got with named placeholders: true1114 // check got w/named placeholders, and children w/go structs: true1115 // check got w/num & named placeholders: true1116}1117func ExampleJSON_embedding() {1118 t := &testing.T{}1119 got := &struct {1120 Fullname string `json:"fullname"`1121 Age int `json:"age"`1122 }{1123 Fullname: "Bob Foobar",1124 Age: 42,1125 }1126 ok := td.Cmp(t, got, td.JSON(`{"age": NotZero(), "fullname": NotEmpty()}`))1127 fmt.Println("check got with simple operators:", ok)1128 ok = td.Cmp(t, got, td.JSON(`{"age": $^NotZero, "fullname": $^NotEmpty}`))1129 fmt.Println("check got with operator shortcuts:", ok)1130 ok = td.Cmp(t, got, td.JSON(`1131{1132 "age": Between(40, 42, "]]"), // in ]40; 42]1133 "fullname": All(1134 HasPrefix("Bob"),1135 HasSuffix("bar") // ← comma is optional here1136 )1137}`))1138 fmt.Println("check got with complex operators:", ok)1139 ok = td.Cmp(t, got, td.JSON(`1140{1141 "age": Between(40, 42, "]["), // in ]40; 42[ → 42 excluded1142 "fullname": All(1143 HasPrefix("Bob"),1144 HasSuffix("bar"),1145 )1146}`))1147 fmt.Println("check got with complex operators:", ok)1148 ok = td.Cmp(t, got, td.JSON(`1149{1150 "age": Between($1, $2, $3), // in ]40; 42]1151 "fullname": All(1152 HasPrefix($4),1153 HasSuffix("bar") // ← comma is optional here1154 )1155}`,1156 40, 42, td.BoundsOutIn,1157 "Bob"))1158 fmt.Println("check got with complex operators, w/placeholder args:", ok)1159 // Output:1160 // check got with simple operators: true1161 // check got with operator shortcuts: true1162 // check got with complex operators: true1163 // check got with complex operators: false1164 // check got with complex operators, w/placeholder args: true1165}1166func ExampleJSON_rawStrings() {1167 t := &testing.T{}1168 type details struct {1169 Address string `json:"address"`1170 Car string `json:"car"`1171 }1172 got := &struct {1173 Fullname string `json:"fullname"`1174 Age int `json:"age"`1175 Details details `json:"details"`1176 }{1177 Fullname: "Foo Bar",1178 Age: 42,1179 Details: details{1180 Address: "something",1181 Car: "Peugeot",1182 },1183 }1184 ok := td.Cmp(t, got,1185 td.JSON(`1186{1187 "fullname": HasPrefix("Foo"),1188 "age": Between(41, 43),1189 "details": SuperMapOf({1190 "address": NotEmpty, // () are optional when no parameters1191 "car": Any("Peugeot", "Tesla", "Jeep") // any of these1192 })1193}`))1194 fmt.Println("Original:", ok)1195 ok = td.Cmp(t, got,1196 td.JSON(`1197{1198 "fullname": "$^HasPrefix(\"Foo\")",1199 "age": "$^Between(41, 43)",1200 "details": "$^SuperMapOf({\n\"address\": NotEmpty,\n\"car\": Any(\"Peugeot\", \"Tesla\", \"Jeep\")\n})"1201}`))1202 fmt.Println("JSON compliant:", ok)1203 ok = td.Cmp(t, got,1204 td.JSON(`1205{1206 "fullname": "$^HasPrefix(\"Foo\")",1207 "age": "$^Between(41, 43)",1208 "details": "$^SuperMapOf({1209 \"address\": NotEmpty, // () are optional when no parameters1210 \"car\": Any(\"Peugeot\", \"Tesla\", \"Jeep\") // any of these1211 })"1212}`))1213 fmt.Println("JSON multilines strings:", ok)1214 ok = td.Cmp(t, got,1215 td.JSON(`1216{1217 "fullname": "$^HasPrefix(r<Foo>)",1218 "age": "$^Between(41, 43)",1219 "details": "$^SuperMapOf({1220 r<address>: NotEmpty, // () are optional when no parameters1221 r<car>: Any(r<Peugeot>, r<Tesla>, r<Jeep>) // any of these1222 })"1223}`))1224 fmt.Println("Raw strings:", ok)1225 // Output:1226 // Original: true1227 // JSON compliant: true1228 // JSON multilines strings: true1229 // Raw strings: true1230}1231func ExampleJSON_file() {1232 t := &testing.T{}1233 got := &struct {1234 Fullname string `json:"fullname"`1235 Age int `json:"age"`1236 Gender string `json:"gender"`1237 }{1238 Fullname: "Bob Foobar",1239 Age: 42,1240 Gender: "male",1241 }1242 tmpDir, err := os.MkdirTemp("", "")1243 if err != nil {1244 t.Fatal(err)1245 }1246 defer os.RemoveAll(tmpDir) // clean up1247 filename := tmpDir + "/test.json"1248 if err = os.WriteFile(filename, []byte(`1249{1250 "fullname": "$name",1251 "age": "$age",1252 "gender": "$gender"1253}`), 0644); err != nil {1254 t.Fatal(err)1255 }1256 // OK let's test with this file1257 ok := td.Cmp(t, got,1258 td.JSON(filename,1259 td.Tag("name", td.HasPrefix("Bob")),1260 td.Tag("age", td.Between(40, 45)),1261 td.Tag("gender", td.Re(`^(male|female)\z`))))1262 fmt.Println("Full match from file name:", ok)1263 // When the file is already open1264 file, err := os.Open(filename)1265 if err != nil {1266 t.Fatal(err)1267 }1268 ok = td.Cmp(t, got,1269 td.JSON(file,1270 td.Tag("name", td.HasPrefix("Bob")),1271 td.Tag("age", td.Between(40, 45)),1272 td.Tag("gender", td.Re(`^(male|female)\z`))))1273 fmt.Println("Full match from io.Reader:", ok)1274 // Output:1275 // Full match from file name: true1276 // Full match from io.Reader: true1277}1278func ExampleJSONPointer_rfc6901() {1279 t := &testing.T{}1280 got := json.RawMessage(`1281{1282 "foo": ["bar", "baz"],1283 "": 0,1284 "a/b": 1,1285 "c%d": 2,1286 "e^f": 3,1287 "g|h": 4,1288 "i\\j": 5,1289 "k\"l": 6,1290 " ": 7,1291 "m~n": 81292}`)1293 expected := map[string]any{1294 "foo": []any{"bar", "baz"},1295 "": 0,1296 "a/b": 1,1297 "c%d": 2,1298 "e^f": 3,1299 "g|h": 4,1300 `i\j`: 5,1301 `k"l`: 6,1302 " ": 7,1303 "m~n": 8,1304 }1305 ok := td.Cmp(t, got, td.JSONPointer("", expected))1306 fmt.Println("Empty JSON pointer means all:", ok)1307 ok = td.Cmp(t, got, td.JSONPointer(`/foo`, []any{"bar", "baz"}))1308 fmt.Println("Extract `foo` key:", ok)1309 ok = td.Cmp(t, got, td.JSONPointer(`/foo/0`, "bar"))1310 fmt.Println("First item of `foo` key slice:", ok)1311 ok = td.Cmp(t, got, td.JSONPointer(`/`, 0))1312 fmt.Println("Empty key:", ok)1313 ok = td.Cmp(t, got, td.JSONPointer(`/a~1b`, 1))1314 fmt.Println("Slash has to be escaped using `~1`:", ok)1315 ok = td.Cmp(t, got, td.JSONPointer(`/c%d`, 2))1316 fmt.Println("% in key:", ok)1317 ok = td.Cmp(t, got, td.JSONPointer(`/e^f`, 3))1318 fmt.Println("^ in key:", ok)1319 ok = td.Cmp(t, got, td.JSONPointer(`/g|h`, 4))1320 fmt.Println("| in key:", ok)1321 ok = td.Cmp(t, got, td.JSONPointer(`/i\j`, 5))1322 fmt.Println("Backslash in key:", ok)1323 ok = td.Cmp(t, got, td.JSONPointer(`/k"l`, 6))1324 fmt.Println("Double-quote in key:", ok)1325 ok = td.Cmp(t, got, td.JSONPointer(`/ `, 7))1326 fmt.Println("Space key:", ok)1327 ok = td.Cmp(t, got, td.JSONPointer(`/m~0n`, 8))1328 fmt.Println("Tilde has to be escaped using `~0`:", ok)1329 // Output:1330 // Empty JSON pointer means all: true1331 // Extract `foo` key: true1332 // First item of `foo` key slice: true1333 // Empty key: true1334 // Slash has to be escaped using `~1`: true1335 // % in key: true1336 // ^ in key: true1337 // | in key: true1338 // Backslash in key: true1339 // Double-quote in key: true1340 // Space key: true1341 // Tilde has to be escaped using `~0`: true1342}1343func ExampleJSONPointer_struct() {1344 t := &testing.T{}1345 // Without json tags, encoding/json uses public fields name1346 type Item struct {1347 Name string1348 Value int641349 Next *Item1350 }1351 got := Item{1352 Name: "first",1353 Value: 1,1354 Next: &Item{1355 Name: "second",1356 Value: 2,1357 Next: &Item{1358 Name: "third",1359 Value: 3,1360 },1361 },1362 }1363 ok := td.Cmp(t, got, td.JSONPointer("/Next/Next/Name", "third"))1364 fmt.Println("3rd item name is `third`:", ok)1365 ok = td.Cmp(t, got, td.JSONPointer("/Next/Next/Value", td.Gte(int64(3))))1366 fmt.Println("3rd item value is greater or equal than 3:", ok)1367 ok = td.Cmp(t, got,1368 td.JSONPointer("/Next",1369 td.JSONPointer("/Next",1370 td.JSONPointer("/Value", td.Gte(int64(3))))))1371 fmt.Println("3rd item value is still greater or equal than 3:", ok)1372 ok = td.Cmp(t, got, td.JSONPointer("/Next/Next/Next/Name", td.Ignore()))1373 fmt.Println("4th item exists and has a name:", ok)1374 // Struct comparison work with or without pointer: &Item{…} works too1375 ok = td.Cmp(t, got, td.JSONPointer("/Next/Next", Item{1376 Name: "third",1377 Value: 3,1378 }))1379 fmt.Println("3rd item full comparison:", ok)1380 // Output:1381 // 3rd item name is `third`: true1382 // 3rd item value is greater or equal than 3: true1383 // 3rd item value is still greater or equal than 3: true1384 // 4th item exists and has a name: false1385 // 3rd item full comparison: true1386}1387func ExampleJSONPointer_has_hasnt() {1388 t := &testing.T{}1389 got := json.RawMessage(`1390{1391 "name": "Bob",1392 "age": 42,1393 "children": [1394 {1395 "name": "Alice",1396 "age": 161397 },1398 {1399 "name": "Britt",1400 "age": 21,1401 "children": [1402 {1403 "name": "John",1404 "age": 11405 }1406 ]1407 }1408 ]1409}`)1410 // Has Bob some children?1411 ok := td.Cmp(t, got, td.JSONPointer("/children", td.Len(td.Gt(0))))1412 fmt.Println("Bob has at least one child:", ok)1413 // But checking "children" exists is enough here1414 ok = td.Cmp(t, got, td.JSONPointer("/children/0/children", td.Ignore()))1415 fmt.Println("Alice has children:", ok)1416 ok = td.Cmp(t, got, td.JSONPointer("/children/1/children", td.Ignore()))1417 fmt.Println("Britt has children:", ok)1418 // The reverse can be checked too1419 ok = td.Cmp(t, got, td.Not(td.JSONPointer("/children/0/children", td.Ignore())))1420 fmt.Println("Alice hasn't children:", ok)1421 ok = td.Cmp(t, got, td.Not(td.JSONPointer("/children/1/children", td.Ignore())))1422 fmt.Println("Britt hasn't children:", ok)1423 // Output:1424 // Bob has at least one child: true1425 // Alice has children: false1426 // Britt has children: true1427 // Alice hasn't children: true1428 // Britt hasn't children: false1429}1430func ExampleKeys() {1431 t := &testing.T{}1432 got := map[string]int{"foo": 1, "bar": 2, "zip": 3}1433 // Keys tests keys in an ordered manner1434 ok := td.Cmp(t, got, td.Keys([]string{"bar", "foo", "zip"}))1435 fmt.Println("All sorted keys are found:", ok)1436 // If the expected keys are not ordered, it fails1437 ok = td.Cmp(t, got, td.Keys([]string{"zip", "bar", "foo"}))1438 fmt.Println("All unsorted keys are found:", ok)1439 // To circumvent that, one can use Bag operator1440 ok = td.Cmp(t, got, td.Keys(td.Bag("zip", "bar", "foo")))1441 fmt.Println("All unsorted keys are found, with the help of Bag operator:", ok)1442 // Check that each key is 3 bytes long1443 ok = td.Cmp(t, got, td.Keys(td.ArrayEach(td.Len(3))))1444 fmt.Println("Each key is 3 bytes long:", ok)1445 // Output:1446 // All sorted keys are found: true1447 // All unsorted keys are found: false1448 // All unsorted keys are found, with the help of Bag operator: true1449 // Each key is 3 bytes long: true1450}1451func ExampleLast_classic() {1452 t := &testing.T{}1453 got := []int{-3, -2, -1, 0, 1, 2, 3}1454 ok := td.Cmp(t, got, td.Last(td.Lt(0), -1))1455 fmt.Println("last negative number is -1:", ok)1456 isEven := func(x int) bool { return x%2 == 0 }1457 ok = td.Cmp(t, got, td.Last(isEven, 2))1458 fmt.Println("last even number is 2:", ok)1459 ok = td.Cmp(t, got, td.Last(isEven, td.Gt(0)))1460 fmt.Println("last even number is > 0:", ok)1461 ok = td.Cmp(t, got, td.Last(isEven, td.Code(isEven)))1462 fmt.Println("last even number is well even:", ok)1463 // Output:1464 // last negative number is -1: true1465 // last even number is 2: true1466 // last even number is > 0: true1467 // last even number is well even: true1468}1469func ExampleLast_empty() {1470 t := &testing.T{}1471 ok := td.Cmp(t, ([]int)(nil), td.Last(td.Gt(0), td.Gt(0)))1472 fmt.Println("last in nil slice:", ok)1473 ok = td.Cmp(t, []int{}, td.Last(td.Gt(0), td.Gt(0)))1474 fmt.Println("last in empty slice:", ok)1475 ok = td.Cmp(t, &[]int{}, td.Last(td.Gt(0), td.Gt(0)))1476 fmt.Println("last in empty pointed slice:", ok)1477 ok = td.Cmp(t, [0]int{}, td.Last(td.Gt(0), td.Gt(0)))1478 fmt.Println("last in empty array:", ok)1479 // Output:1480 // last in nil slice: false1481 // last in empty slice: false1482 // last in empty pointed slice: false1483 // last in empty array: false1484}1485func ExampleLast_struct() {1486 t := &testing.T{}1487 type Person struct {1488 Fullname string `json:"fullname"`1489 Age int `json:"age"`1490 }1491 got := []*Person{1492 {1493 Fullname: "Bob Foobar",1494 Age: 42,1495 },1496 {1497 Fullname: "Alice Bingo",1498 Age: 37,1499 },1500 }1501 ok := td.Cmp(t, got, td.Last(1502 td.Smuggle("Age", td.Gt(30)),1503 td.Smuggle("Fullname", "Alice Bingo")))1504 fmt.Println("last person.Age > 30 → Alice:", ok)1505 ok = td.Cmp(t, got, td.Last(1506 td.JSONPointer("/age", td.Gt(30)),1507 td.SuperJSONOf(`{"fullname":"Alice Bingo"}`)))1508 fmt.Println("last person.Age > 30 → Alice, using JSON:", ok)1509 ok = td.Cmp(t, got, td.Last(1510 td.JSONPointer("/age", td.Gt(30)),1511 td.JSONPointer("/fullname", td.HasPrefix("Alice"))))1512 fmt.Println("first person.Age > 30 → Alice, using JSONPointer:", ok)1513 // Output:1514 // last person.Age > 30 → Alice: true1515 // last person.Age > 30 → Alice, using JSON: true1516 // first person.Age > 30 → Alice, using JSONPointer: true1517}1518func ExampleLast_json() {1519 t := &testing.T{}1520 got := map[string]any{1521 "values": []int{1, 2, 3, 4},1522 }1523 ok := td.Cmp(t, got, td.JSON(`{"values": Last(Lt(3), 2)}`))1524 fmt.Println("last number < 3:", ok)1525 got = map[string]any{1526 "persons": []map[string]any{1527 {"id": 1, "name": "Joe"},1528 {"id": 2, "name": "Bob"},1529 {"id": 3, "name": "Alice"},1530 {"id": 4, "name": "Brian"},1531 {"id": 5, "name": "Britt"},1532 },1533 }1534 ok = td.Cmp(t, got, td.JSON(`1535{1536 "persons": Last(JSONPointer("/name", "Brian"), {"id": 4, "name": "Brian"})1537}`))1538 fmt.Println(`is "Brian" content OK:`, ok)1539 ok = td.Cmp(t, got, td.JSON(`1540{1541 "persons": Last(JSONPointer("/name", "Brian"), JSONPointer("/id", 4))1542}`))1543 fmt.Println(`ID of "Brian" is 4:`, ok)1544 // Output:1545 // last number < 3: true1546 // is "Brian" content OK: true1547 // ID of "Brian" is 4: true1548}1549func ExampleLax() {1550 t := &testing.T{}1551 gotInt64 := int64(1234)1552 gotInt32 := int32(1235)1553 type myInt uint161554 gotMyInt := myInt(1236)1555 expected := td.Between(1230, 1240) // int type here...

Full Screen

Full Screen

td_json_pointer_test.go

Source:td_json_pointer_test.go Github

copy

Full Screen

...19func (j *jsonPtrMap) UnmarshalJSON(b []byte) error {20 return json.Unmarshal(b, (*map[string]any)(j))21}22var _ = []json.Unmarshaler{jsonPtrTest(0), &jsonPtrMap{}}23func TestJSONPointer(t *testing.T) {24 //25 // nil26 t.Run("nil", func(t *testing.T) {27 checkOK(t, nil, td.JSONPointer("", nil))28 checkOK(t, (*int)(nil), td.JSONPointer("", nil))29 // Yes encoding/json succeeds to unmarshal nil into an int30 checkOK(t, nil, td.JSONPointer("", 0))31 checkOK(t, (*int)(nil), td.JSONPointer("", 0))32 checkError(t, map[string]int{"foo": 42}, td.JSONPointer("/foo", nil),33 expectedError{34 Message: mustBe("values differ"),35 Path: mustBe("DATA.JSONPointer</foo>"),36 Got: mustBe(`42.0`),37 Expected: mustBe(`nil`),38 })39 // As encoding/json succeeds to unmarshal nil into an int40 checkError(t, map[string]any{"foo": nil}, td.JSONPointer("/foo", 1),41 expectedError{42 Message: mustBe("values differ"),43 Path: mustBe("DATA.JSONPointer</foo>"),44 Got: mustBe(`0`), // as an int is expected, nil becomes 045 Expected: mustBe(`1`),46 })47 })48 //49 // Basic types50 t.Run("basic types", func(t *testing.T) {51 checkOK(t, 123, td.JSONPointer("", 123))52 checkOK(t, 123, td.JSONPointer("", td.Between(120, 130)))53 checkOK(t, true, td.JSONPointer("", true))54 })55 //56 // More complex type with encoding/json tags57 t.Run("complex type with json tags", func(t *testing.T) {58 type jpStruct struct {59 Slice []string `json:"slice,omitempty"`60 Map map[string]*jpStruct `json:"map,omitempty"`61 Num int `json:"num"`62 Bool bool `json:"bool"`63 Str string `json:"str,omitempty"`64 }65 got := jpStruct{66 Slice: []string{"bar", "baz"},67 Map: map[string]*jpStruct{68 "test": {69 Num: 2,70 Str: "level2",71 },72 },73 Num: 1,74 Bool: true,75 Str: "level1",76 }77 // No filter, should match got or its map representation78 checkOK(t, got, td.JSONPointer("",79 map[string]any{80 "slice": []any{"bar", "baz"},81 "map": map[string]any{82 "test": map[string]any{83 "num": 2,84 "str": "level2",85 "bool": false,86 },87 },88 "num": int64(1), // should be OK as Lax is enabled89 "bool": true,90 "str": "level1",91 }))92 checkOK(t, got, td.JSONPointer("", got))93 checkOK(t, got, td.JSONPointer("", &got))94 // A specific field95 checkOK(t, got, td.JSONPointer("/num", int64(1))) // Lax enabled96 checkOK(t, got, td.JSONPointer("/slice/1", "baz"))97 checkOK(t, got, td.JSONPointer("/map/test/num", 2))98 checkOK(t, got, td.JSONPointer("/map/test/str", td.Contains("vel2")))99 checkOK(t, got,100 td.JSONPointer("/map", td.JSONPointer("/test", td.JSONPointer("/num", 2))))101 checkError(t, got, td.JSONPointer("/zzz/pipo", 666),102 expectedError{103 Message: mustBe("cannot retrieve value via JSON pointer"),104 Path: mustBe("DATA.JSONPointer</zzz>"),105 Summary: mustBe("key not found"),106 })107 checkError(t, got, td.JSONPointer("/num/pipo", 666),108 expectedError{109 Message: mustBe("cannot retrieve value via JSON pointer"),110 Path: mustBe("DATA.JSONPointer</num/pipo>"),111 Summary: mustBe("not a map nor an array"),112 })113 checkError(t, got, td.JSONPointer("/slice/2", "zip"),114 expectedError{115 Message: mustBe("cannot retrieve value via JSON pointer"),116 Path: mustBe("DATA.JSONPointer</slice/2>"),117 Summary: mustBe("out of array range"),118 })119 checkError(t, got, td.JSONPointer("/slice/xxx", "zip"),120 expectedError{121 Message: mustBe("cannot retrieve value via JSON pointer"),122 Path: mustBe("DATA.JSONPointer</slice/xxx>"),123 Summary: mustBe("array but not an index in JSON pointer"),124 })125 checkError(t, got, td.JSONPointer("/slice/1", "zip"),126 expectedError{127 Message: mustBe("values differ"),128 Path: mustBe("DATA.JSONPointer</slice/1>"),129 Got: mustBe(`"baz"`),130 Expected: mustBe(`"zip"`),131 })132 // A struct behind a specific field133 checkOK(t, got, td.JSONPointer("/map/test", map[string]any{134 "num": 2,135 "str": "level2",136 "bool": false,137 }))138 checkOK(t, got, td.JSONPointer("/map/test", jpStruct{139 Num: 2,140 Str: "level2",141 }))142 checkOK(t, got, td.JSONPointer("/map/test", &jpStruct{143 Num: 2,144 Str: "level2",145 }))146 checkOK(t, got, td.JSONPointer("/map/test", td.Struct(&jpStruct{147 Num: 2,148 Str: "level2",149 }, nil)))150 })151 //152 // Complex type without encoding/json tags153 t.Run("complex type without json tags", func(t *testing.T) {154 type jpStruct struct {155 Slice []string156 Map map[string]*jpStruct157 Num int158 Bool bool159 Str string160 }161 got := jpStruct{162 Slice: []string{"bar", "baz"},163 Map: map[string]*jpStruct{164 "test": {165 Num: 2,166 Str: "level2",167 },168 },169 Num: 1,170 Bool: true,171 Str: "level1",172 }173 checkOK(t, got, td.JSONPointer("/Num", 1))174 checkOK(t, got, td.JSONPointer("/Slice/1", "baz"))175 checkOK(t, got, td.JSONPointer("/Map/test/Num", 2))176 checkOK(t, got, td.JSONPointer("/Map/test/Str", td.Contains("vel2")))177 })178 //179 // Chained list180 t.Run("Chained list", func(t *testing.T) {181 type Item struct {182 Val int `json:"val"`183 Next *Item `json:"next"`184 }185 got := Item{Val: 1, Next: &Item{Val: 2, Next: &Item{Val: 3}}}186 checkOK(t, got, td.JSONPointer("/next/next", Item{Val: 3}))187 checkOK(t, got, td.JSONPointer("/next/next", &Item{Val: 3}))188 checkOK(t, got,189 td.JSONPointer("/next/next",190 td.Struct(Item{}, td.StructFields{"Val": td.Gte(3)})))191 checkOK(t, json.RawMessage(`{"foo":{"bar": {"zip": true}}}`),192 td.JSONPointer("/foo/bar", td.JSON(`{"zip": true}`)))193 })194 //195 // Lax cases196 t.Run("Lax", func(t *testing.T) {197 t.Run("json.Unmarshaler", func(t *testing.T) {198 got := jsonPtrMap{"x": 123}199 checkOK(t, got, td.JSONPointer("", jsonPtrMap{"x": float64(123)}))200 checkOK(t, got, td.JSONPointer("", &jsonPtrMap{"x": float64(123)}))201 checkOK(t, got, td.JSONPointer("", got))202 checkOK(t, got, td.JSONPointer("", &got))203 })204 t.Run("struct", func(t *testing.T) {205 type jpStruct struct {206 Num any207 }208 got := jpStruct{Num: 123}209 checkOK(t, got, td.JSONPointer("", jpStruct{Num: float64(123)}))210 checkOK(t, jpStruct{Num: got}, td.JSONPointer("/Num", jpStruct{Num: float64(123)}))211 checkOK(t, got, td.JSONPointer("", got))212 checkOK(t, got, td.JSONPointer("", &got))213 expected := int8(123)214 checkOK(t, got, td.JSONPointer("/Num", expected))215 checkOK(t, got, td.JSONPointer("/Num", &expected))216 })217 })218 //219 // Errors220 t.Run("errors", func(t *testing.T) {221 checkError(t, func() {}, td.JSONPointer("", td.NotNil()),222 expectedError{223 Message: mustBe("json.Marshal failed"),224 Path: mustBe("DATA"),225 Summary: mustContain("json: unsupported type"),226 })227 checkError(t,228 map[string]int{"zzz": 42},229 td.JSONPointer("/zzz", jsonPtrTest(56)),230 expectedError{231 Message: mustBe("an error occurred while unmarshalling JSON into td_test.jsonPtrTest"),232 Path: mustBe("DATA.JSONPointer</zzz>"),233 Summary: mustBe("jsonPtrTest unmarshal custom error"),234 })235 })236 //237 // Bad usage238 checkError(t, "never tested",239 td.JSONPointer("x", 1234),240 expectedError{241 Message: mustBe("bad usage of JSONPointer operator"),242 Path: mustBe("DATA"),243 Summary: mustBe(`bad JSON pointer "x"`),244 })245 //246 // String247 test.EqualStr(t, td.JSONPointer("/x", td.Gt(2)).String(),248 "JSONPointer(/x, > 2)")249 test.EqualStr(t, td.JSONPointer("/x", 2).String(),250 "JSONPointer(/x, 2)")251 test.EqualStr(t, td.JSONPointer("/x", nil).String(),252 "JSONPointer(/x, nil)")253 // Erroneous op254 test.EqualStr(t, td.JSONPointer("x", 1234).String(), "JSONPointer(<ERROR>)")255}256func TestJSONPointerTypeBehind(t *testing.T) {257 equalTypes(t, td.JSONPointer("", 42), nil)258 // Erroneous op259 equalTypes(t, td.JSONPointer("x", 1234), nil)260}...

Full Screen

Full Screen

td_json_pointer.go

Source:td_json_pointer.go Github

copy

Full Screen

...10 "strings"11 "github.com/maxatome/go-testdeep/internal/ctxerr"12 "github.com/maxatome/go-testdeep/internal/util"13)14type tdJSONPointer struct {15 tdSmugglerBase16 pointer string17}18var _ TestDeep = &tdJSONPointer{}19// summary(JSONPointer): compares against JSON representation using a20// JSON pointer21// input(JSONPointer): nil,bool,str,int,float,array,slice,map,struct,ptr22// JSONPointer is a smuggler operator. It takes the JSON23// representation of data, gets the value corresponding to the JSON24// pointer ptr (as [RFC 6901] specifies it) and compares it to25// expectedValue.26//27// [Lax] mode is automatically enabled to simplify numeric tests.28//29// JSONPointer does its best to convert back the JSON pointed data to30// the type of expectedValue or to the type behind the31// expectedValue operator, if it is an operator. Allowing to do32// things like:33//34// type Item struct {35// Val int `json:"val"`36// Next *Item `json:"next"`37// }38// got := Item{Val: 1, Next: &Item{Val: 2, Next: &Item{Val: 3}}}39//40// td.Cmp(t, got, td.JSONPointer("/next/next", Item{Val: 3}))41// td.Cmp(t, got, td.JSONPointer("/next/next", &Item{Val: 3}))42// td.Cmp(t,43// got,44// td.JSONPointer("/next/next",45// td.Struct(Item{}, td.StructFields{"Val": td.Gte(3)})),46// )47//48// got := map[string]int64{"zzz": 42} // 42 is int64 here49// td.Cmp(t, got, td.JSONPointer("/zzz", 42))50// td.Cmp(t, got, td.JSONPointer("/zzz", td.Between(40, 45)))51//52// Of course, it does this conversion only if the expected type can be53// guessed. In the case the conversion cannot occur, data is compared54// as is, in its freshly unmarshaled JSON form (so as bool, float64,55// string, []any, map[string]any or simply nil).56//57// Note that as any [TestDeep] operator can be used as expectedValue,58// [JSON] operator works out of the box:59//60// got := json.RawMessage(`{"foo":{"bar": {"zip": true}}}`)61// td.Cmp(t, got, td.JSONPointer("/foo/bar", td.JSON(`{"zip": true}`)))62//63// It can be used with structs lacking json tags. In this case, fields64// names have to be used in JSON pointer:65//66// type Item struct {67// Val int68// Next *Item69// }70// got := Item{Val: 1, Next: &Item{Val: 2, Next: &Item{Val: 3}}}71//72// td.Cmp(t, got, td.JSONPointer("/Next/Next", Item{Val: 3}))73//74// Contrary to [Smuggle] operator and its fields-path feature, only75// public fields can be followed, as private ones are never (un)marshaled.76//77// There is no JSONHas nor JSONHasnt operators to only check a JSON78// pointer exists or not, but they can easily be emulated:79//80// JSONHas := func(pointer string) td.TestDeep {81// return td.JSONPointer(pointer, td.Ignore())82// }83//84// JSONHasnt := func(pointer string) td.TestDeep {85// return td.Not(td.JSONPointer(pointer, td.Ignore()))86// }87//88// TypeBehind method always returns nil as the expected type cannot be89// guessed from a JSON pointer.90//91// See also [JSON], [SubJSONOf], [SuperJSONOf] and [Smuggle].92//93// [RFC 6901]: https://tools.ietf.org/html/rfc690194func JSONPointer(ptr string, expectedValue any) TestDeep {95 p := tdJSONPointer{96 tdSmugglerBase: newSmugglerBase(expectedValue),97 pointer: ptr,98 }99 if !strings.HasPrefix(ptr, "/") && ptr != "" {100 p.err = ctxerr.OpBad("JSONPointer", "bad JSON pointer %q", ptr)101 return &p102 }103 if !p.isTestDeeper {104 p.expectedValue = reflect.ValueOf(expectedValue)105 }106 return &p107}108func (p *tdJSONPointer) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {109 if p.err != nil {110 return ctx.CollectError(p.err)111 }112 vgot, eErr := jsonify(ctx, got)113 if eErr != nil {114 return ctx.CollectError(eErr)115 }116 vgot, err := util.JSONPointer(vgot, p.pointer)117 if err != nil {118 if ctx.BooleanError {119 return ctxerr.BooleanError120 }121 pErr := err.(*util.JSONPointerError)122 ctx = jsonPointerContext(ctx, pErr.Pointer)123 return ctx.CollectError(&ctxerr.Error{124 Message: "cannot retrieve value via JSON pointer",125 Summary: ctxerr.NewSummary(pErr.Type),126 })127 }128 // Here, vgot type is either a bool, float64, string,129 // []any, a map[string]any or simply nil130 ctx = jsonPointerContext(ctx, p.pointer)131 ctx.BeLax = true132 return p.jsonValueEqual(ctx, vgot)133}134func (p *tdJSONPointer) String() string {135 if p.err != nil {136 return p.stringError()137 }138 var expected string139 switch {140 case p.isTestDeeper:141 expected = p.expectedValue.Interface().(TestDeep).String()142 case p.expectedValue.IsValid():143 expected = util.ToString(p.expectedValue.Interface())144 default:145 expected = "nil"146 }147 return fmt.Sprintf("JSONPointer(%s, %s)", p.pointer, expected)148}149func (p *tdJSONPointer) HandleInvalid() bool {150 return true151}152func jsonPointerContext(ctx ctxerr.Context, pointer string) ctxerr.Context {153 return ctx.AddCustomLevel(".JSONPointer<" + pointer + ">")154}...

Full Screen

Full Screen

JSONPointer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 data := []byte(`{"name":{"first":"Janet","last":"Prichard"},"age":47}`)4 value, dataType, offset, err := jsonparser.Get(data, "name", "first")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(string(value), dataType, offset)9}10Example 3: Get() method with JSONPointer11import (12func main() {13 data := []byte(`{"name":{"first":"Janet","last":"Prichard"},"age":47}`)14 value, dataType, offset, err := jsonparser.Get(data, "name", "first")15 if err != nil {16 fmt.Println(err)17 }18 fmt.Println(string(value), dataType, offset)19}20Example 4: Get() method with JSONPointer and defaultValue21import (22func main() {23 data := []byte(`{"name":{"first":"Janet","last":"Prichard"},"age":47}`)24 value, dataType, offset, err := jsonparser.Get(data, "name", "first", "default")25 if err != nil {26 fmt.Println(err)27 }28 fmt.Println(string(value), dataType, offset)29}30Example 5: Get() method with JSONPointer and defaultValue31import (32func main() {33 data := []byte(`{"name":{"first":"Janet","last":"Prichard"},"age":47}`)34 value, dataType, offset, err := jsonparser.Get(data, "name", "first", "default")35 if err != nil {36 fmt.Println(err)37 }38 fmt.Println(string(value), dataType, offset)39}

Full Screen

Full Screen

JSONPointer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 json := []byte(`{"name": {"first": "Janet", "last": "Prichard"}, "age": 47}`)4 value, dataType, offset, err := jsonparser.Get(json, "name", "first")5 if err == nil {6 fmt.Println("First name:", string(value), "Type:", dataType, "Offset:", offset)7 }8}9JSONPointer(json, pointer)10import (11func main() {12 json := []byte(`{"name": {"first": "Janet", "last": "Prichard"}, "age": 47}`)13 value, dataType, offset, err := jsonparser.Get(json, "name", "first")14 if err == nil {15 fmt.Println("First name:", string(value), "Type:", dataType, "Offset:", offset)16 }17}18JSONEachKey(json, callback, keysToSearch)19callback: func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error20import (21func main() {22 json := []byte(`{"name": {"first": "Janet", "last": "Prichard"}, "age": 47}`)23 jsonparser.ObjectEach(json, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {24 fmt.Println("Key:", string(key), "Value:", string(value), "Type:", dataType, "Offset:", offset)25 })26}27Key: name Value: {"first":"Janet","last":"Prichard"} Type: object Offset: 8

Full Screen

Full Screen

JSONPointer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 data := []byte(`{"name":"Wednesday","age":6,"parents":["Gomez","Morticia"]}`)4 value, dataType, offset, err := jsonparser.Get(data, "name")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println("value:", string(value), "dataType:", dataType, "offset:", offset)9 value, dataType, offset, err = jsonparser.Get(data, "age")10 if err != nil {11 fmt.Println(err)12 }13 fmt.Println("value:", string(value), "dataType:", dataType, "offset:", offset)14 value, dataType, offset, err = jsonparser.Get(data, "parents")15 if err != nil {16 fmt.Println(err)17 }18 fmt.Println("value:", string(value), "dataType:", dataType, "offset:", offset)19 value, dataType, offset, err = jsonparser.Get(data, "parents", "[0]")20 if err != nil {21 fmt.Println(err)22 }23 fmt.Println("value:", string(value), "dataType:", dataType, "offset:", offset)24 value, dataType, offset, err = jsonparser.Get(data, "parents", "[1]")25 if err != nil {26 fmt.Println(err)27 }28 fmt.Println("value:", string(value), "dataType:", dataType, "offset:", offset)29}30Get(data []byte, pointer string, keys ...string) (value []byte, dataType jsonparser.ValueType, offset int, err error)31import (32func main() {33 data := []byte(`{"name":"Wednesday","age":6,"parents":["Gomez","Morticia"]}`)

Full Screen

Full Screen

JSONPointer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 data := []byte(`{"name": "Antonio", "age": 30, "city": "London"}`)4 value, dataType, offset, err := jsonparser.Get(data, "name")5 fmt.Println(string(value), dataType, offset, err)6}7jsonparser.Get() is a safe method that creates a copy of the underlying data. jsonparser.GetBoolean() is a safe method that creates a copy of the underlying data. The difference between jsonparser.Get() and jsonparser.GetBoolean() is that jsonparser.Get() returns the value of the

Full Screen

Full Screen

JSONPointer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 data := []byte(`{"a": {"b": "c"}}`)5 value, dataType, offset, err := jsonparser.Get(data, "a", "b")6 fmt.Println(string(value), dataType, offset, err)7}8import (9func main() {10 fmt.Println("Hello World!")11 data := []byte(`{"a": {"b": "c"}}`)12 value, dataType, offset, err := jsonparser.Get(data, "a", "b")13 fmt.Println(string(value), dataType, offset, err)14}15import (16func main() {17 fmt.Println("Hello World!")18 data := []byte(`{"a": {"b": "c"}}`)19 value, dataType, offset, err := jsonparser.Get(data, "a", "b")20 fmt.Println(string(value), dataType, offset, err)21}22import (23func main() {24 fmt.Println("Hello World!")25 data := []byte(`{"a": {"b": "c"}}`)26 value, dataType, offset, err := jsonparser.Get(data, "a", "b")27 fmt.Println(string(value), dataType, offset, err)28}29import (30func main() {31 fmt.Println("Hello World!")32 data := []byte(`{"a": {"b": "c"}}`)33 value, dataType, offset, err := jsonparser.Get(data, "a", "b")34 fmt.Println(string(value), dataType, offset, err)35}36import (37func main() {38 fmt.Println("Hello World!")39 data := []byte(`{"a": {"b

Full Screen

Full Screen

JSONPointer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 td := ld.NewTripleDocument()4 fmt.Println(td.JSONPointer("/0/subject"))5}6import (7func main() {8 td := ld.NewTripleDocument()9 fmt.Println(td.JSONLD())10}11import (12func main() {13 td := ld.NewTripleDocument()14 fmt.Println(td.NQuads())15}16import (17func main() {18 td := ld.NewTripleDocument()19 fmt.Println(td.NTriples())20}21import (22func main() {23 td := ld.NewTripleDocument()

Full Screen

Full Screen

JSONPointer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 data := []byte(`{4 "foo": {5 }6 }`)7 var td interface{}8 json.Unmarshal(data, &td)9 foo, _ := jsonpointer.Get(td, "/foo")10 fmt.Println(foo)11 bar, _ := jsonpointer.Get(td, "/foo/bar")12 fmt.Println(bar)13}

Full Screen

Full Screen

JSONPointer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 data := []byte(`{"user": {"name": "Alex", "age": 20, "phones": ["+44 1234567", "+44 2345678"]}}`)4 value, dataType, offset, err := jsonparser.Get(data, "user", "name")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(string(value), dataType, offset)9 value, dataType, offset, err = jsonparser.Get(data, "user", "phones", "[0]")10 if err != nil {11 fmt.Println(err)12 }13 fmt.Println(string(value), dataType, offset)14}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Go-testdeep automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful