Java Code Examples for com.jayway.jsonpath.DocumentContext#read()
The following examples show how to use
com.jayway.jsonpath.DocumentContext#read() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonPathEvaluator.java From nifi with Apache License 2.0 | 6 votes |
@Override public QueryResult<String> evaluate(EvaluationContext context) { DocumentContext documentContext = getDocumentContext(context); final JsonPath compiledJsonPath = getJsonPath(context); Object result = null; try { result = documentContext.read(compiledJsonPath); } catch (PathNotFoundException pnf) { // it is valid for a path not to be found, keys may not be there // do not spam the error log for this, instead we can log debug if enabled if (LOGGER.isDebugEnabled()) { LOGGER.debug("PathNotFoundException for JsonPath " + compiledJsonPath.getPath(), pnf); } return EMPTY_RESULT; } catch (Exception e) { // a failure for something *other* than path not found however, should at least be // logged. LOGGER.error("Exception while reading JsonPath " + compiledJsonPath.getPath(), e); return EMPTY_RESULT; } return new StringQueryResult(getResultRepresentation(result, EMPTY_RESULT.getValue())); }
Example 2
Source File: ScriptValueTest.java From karate with MIT License | 6 votes |
@Test public void testTypeDetection() { DocumentContext doc = JsonPath.parse("{ foo: 'bar' }"); ScriptValue sv = new ScriptValue(doc); assertEquals(JSON, sv.getType()); doc = JsonPath.parse("[1, 2]"); sv = new ScriptValue(doc); assertEquals(JSON, sv.getType()); Object temp = doc.read("$"); assertTrue(temp instanceof List); sv = new ScriptValue(1); assertTrue(sv.isPrimitive()); assertTrue(sv.isNumber()); assertEquals(1, sv.getAsNumber().intValue()); sv = new ScriptValue(100L); assertTrue(sv.isPrimitive()); assertTrue(sv.isNumber()); assertEquals(100, sv.getAsNumber().longValue()); sv = new ScriptValue(1.0); assertTrue(sv.isPrimitive()); assertTrue(sv.isNumber()); assertEquals(1.0, sv.getAsNumber().doubleValue(), 0); }
Example 3
Source File: JSONIOTest.java From pom-manipulation-ext with Apache License 2.0 | 6 votes |
@Test public void countMatches () throws ManipulationException { String pluginsPath = "$..plugins"; String reposURLPath = "$.repository.url"; try { DocumentContext doc = jsonIO.parseJSON( pluginFile ); List o = doc.read ( pluginsPath ); assertEquals( 1, o.size() ); o = doc.read ( reposURLPath ); assertEquals( 1, o.size() ); } catch (JsonPathException e) { throw new ManipulationException( "Caught JsonPath", e ); } }
Example 4
Source File: Script.java From karate with MIT License | 5 votes |
public static ScriptValue evalJsonPathOnVarByName(String name, String exp, ScenarioContext context) { ScriptValue value = getValuebyName(name, context); if (value.isJsonLike()) { DocumentContext jsonDoc = value.getAsJsonDocument(); return new ScriptValue(jsonDoc.read(exp)); } else if (value.isXml()) { Document xml = value.getValue(Document.class); DocumentContext xmlDoc = XmlUtils.toJsonDoc(xml); return new ScriptValue(xmlDoc.read(exp)); } else { String str = value.getAsString(); DocumentContext strDoc = JsonPath.parse(str); return new ScriptValue(strDoc.read(exp)); } }
Example 5
Source File: JsonUtilsTest.java From karate with MIT License | 5 votes |
@Test public void testJsonChunkByPath() { String raw = "[{ foo: 'bar' }]"; DocumentContext doc = JsonUtils.toJsonDoc(raw); Map map = doc.read("$[0]"); DocumentContext foo = JsonPath.parse(map); assertEquals("{\"foo\":\"bar\"}", foo.jsonString()); }
Example 6
Source File: JsonUtilsTest.java From karate with MIT License | 5 votes |
@Test public void testNonStrictJsonParsing() { String raw = "{ foo: 'bar' }"; DocumentContext dc = JsonUtils.toJsonDoc(raw); logger.debug("parsed json: {}", dc.jsonString()); String value = dc.read("$.foo"); assertEquals("bar", value); }
Example 7
Source File: ScriptValue.java From karate with MIT License | 5 votes |
public Object getAfterConvertingFromJsonOrXmlIfNeeded() { switch (type) { case JSON: DocumentContext json = getValue(DocumentContext.class); return json.read("$"); case XML: Node xml = getValue(Node.class); return XmlUtils.toObject(xml); default: return getValue(); } }
Example 8
Source File: ScriptValue.java From karate with MIT License | 5 votes |
public Map<String, Object> getAsMap() { switch (type) { case MAP: return getValue(Map.class); case JSON: DocumentContext json = getValue(DocumentContext.class); return json.read("$"); case XML: Node xml = getValue(Node.class); return (Map) XmlUtils.toObject(xml); default: throw new RuntimeException("cannot convert to map: " + this); } }
Example 9
Source File: UserGenerationTest.java From credhub with Apache License 2.0 | 5 votes |
@Test public void whenGivenPasswordParameters_shouldGeneratePasswordFromParameters() throws Exception { final MockHttpServletRequestBuilder post = post("/api/v1/data") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) .content("{" + "\"name\": \"" + credentialName1 + "\"," + "\"type\": \"user\"," + "\"parameters\": {" + "\"length\": 40," + "\"exclude_upper\": true," + "\"exclude_lower\": true," + "\"exclude_number\": false," + "\"include_special\": false" + "}" + "}" ); final MockHttpServletResponse response = this.mockMvc.perform(post).andExpect(status() .isOk()).andReturn().getResponse(); final DocumentContext parsedResponse = JsonPath.parse(response.getContentAsString()); final String password = parsedResponse.read("$.value.password"); assertThat(password.length(), equalTo(40)); assertThat(isDigits(password), equalTo(true)); final String username = parsedResponse.read("$.value.username"); assertThat(username.length(), equalTo(20)); assertThat(username.chars().allMatch(Character::isLetter), equalTo(true)); }
Example 10
Source File: JsonUtils.java From karate with MIT License | 5 votes |
public static boolean pathExists(DocumentContext doc, String path) { try { return doc.read(path) != null; } catch (PathNotFoundException pnfe) { return false; } }
Example 11
Source File: TestJsonPath.java From jframe with Apache License 2.0 | 5 votes |
@Test public void testRead() { String json = "{\"_scroll_id\":\"cXVlcnlBbmRGZXRjaDsxOzE2NTUwMDc6c0x6bWo0eERTSTZyYUdZVG9LYThfQTswOw==\",\"took\":2994,\"timed_out\":false,\"_shards\":{\"total\":1,\"successful\":1,\"failed\":0},\"hits\":{\"total\":117375727,\"max_score\":null,\"hits\":[{\"_index\":\"weike\",\"_type\":\"member\",\"_id\":\"AVeslHLGT4gPDlYJn1J2\",\"_score\":null,\"_source\":{\"birthday\":0,\"lm\":1447897716678,\"creditLevel\":0,\"relationSource\":0,\"fstp\":0,\"lt\":0,\"itemCloseCount\":0,\"type\":0,\"tradeFroms\":[\"WAP\"],\"tc\":0,\"ta\":0,\"minp\":0,\"province\":13,\"buyerNick\":\"闽丫丫\",\"receiverName\":\"陆小姐\",\"grade\":0,\"tradeAmount\":102.48,\"closeTradeAmount\":0,\"ft\":0,\"black\":false,\"itemNum\":1,\"closeTradeCount\":0,\"lastEdmTime\":0,\"hasRefund\":true,\"buyerId\":0,\"emailType\":2,\"avgPrice\":102.48,\"giveNBRate\":false,\"lastCouponTimeEnd\":0,\"tradeCount\":1,\"email\":\"[email protected]\",\"ap\":0,\"address\":\"莲前街道新景中心B2010\",\"items\":[523045242297],\"sellerId\":479184430,\"registered\":0,\"goodRate\":0,\"lastTradeTime\":1447256536000,\"lastSmsTime\":0,\"bizOrderId\":1403847313137758,\"maxp\":0,\"mobile\":\"18659211097\"},\"sort\":[0]},{\"_index\":\"weike\",\"_type\":\"member\",\"_id\":\"AVeslHLGT4gPDlYJn1J3\",\"_score\":null,\"_source\":{\"birthday\":0,\"lm\":1448650655763,\"creditLevel\":0,\"relationSource\":1,\"fstp\":0,\"lt\":0,\"itemCloseCount\":0,\"type\":0,\"city\":\"150100\",\"tradeFroms\":[\"WAP\"],\"tc\":0,\"ta\":0,\"minp\":0,\"province\":150000,\"buyerNick\":\"pengran0727\",\"receiverName\":\"彭冉\",\"grade\":1,\"tradeAmount\":238.63,\"closeTradeAmount\":0,\"ft\":0,\"black\":false,\"itemNum\":2,\"status\":\"normal\",\"lastEdmTime\":0,\"closeTradeCount\":0,\"hasRefund\":false,\"buyerId\":0,\"emailType\":0,\"groupIds\":\"418525357\",\"avgPrice\":238.63,\"giveNBRate\":false,\"lastCouponTimeEnd\":0,\"tradeCount\":1,\"ap\":0,\"address\":\"新华西街新华桥农行营业厅(监狱管理局西侧)\",\"items\":[522190672466,522917969407],\"sellerId\":479184430,\"registered\":0,\"goodRate\":0,\"lastTradeTime\":1447256537000,\"lastSmsTime\":0,\"bizOrderId\":0,\"maxp\":0,\"mobile\":\"13624848066\"},\"sort\":[1]}]}}"; long start = System.currentTimeMillis(); DocumentContext context = JsonPath.parse(json); List<MemberDO> source = context.read("$.hits.hits.._source"); String scrollId = context.read("$._scroll_id"); int total = context.<Integer> read("$.hits.total"); System.out.println(System.currentTimeMillis() - start); // System.out.println(scrollId); System.out.println(total); // System.out.println(source); start = System.currentTimeMillis(); Gson gson = new Gson(); Map<String, String> obj = gson.fromJson(json, HashMap.class); System.out.println(System.currentTimeMillis() - start); System.out.println(obj.get("_scroll_id")); // System.out.println((obj.get("hits")).get("total")); // System.out.println(source); List<Map<String, String>> list = new LinkedList<Map<String, String>>(); Map map = new HashMap<>(); map.put("a", "1"); list.add(map); map = new HashMap<>(); map.put("a", "2"); list.add(map); json = Gson.toJson(list); context = JsonPath.parse(json); System.out.println(context.<List> read("$..a")); }
Example 12
Source File: ScriptTest.java From karate with MIT License | 5 votes |
@Test public void testJsonCyclicReferences() { ScenarioContext ctx = getContext(); Script.assign("fun", "function(){ var env = 'dev'; var config = { env: env }; return config }", ctx); Script.assign("json", "fun()", ctx); Map value = (Map) ctx.vars.get("json").getValue(); value.put("child", value); value = JsonUtils.removeCyclicReferences(value); DocumentContext doc = JsonUtils.toJsonDoc(value); Map temp = doc.read("$"); Match.equals(temp, "{ env: 'dev', child: '#java.util.LinkedHashMap' }"); }
Example 13
Source File: ServiceIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenCompleteStructure_whenCalculatingTotalRevenue_thenSucceed() { DocumentContext context = JsonPath.parse(jsonString); int length = context.read("$.length()"); long revenue = 0; for (int i = 0; i < length; i++) { revenue += context.read("$[" + i + "]['box office']", Long.class); } assertEquals(594275385L + 591692078L + 1110526981L + 879376275L, revenue); }
Example 14
Source File: GreetingApiIntegrationTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test @TestsNotMeantForZowe public void shouldCallDiscoverableServiceApi() throws Exception { // When final HttpResponse response = HttpRequestUtils.getResponse("/api/v1/discoverableclient/greeting", SC_OK); final String jsonResponse = EntityUtils.toString(response.getEntity()); DocumentContext jsonContext = JsonPath.parse(jsonResponse); String content = jsonContext.read("$.content"); // Then assertThat(content, equalTo("Hello, world!")); }
Example 15
Source File: ApiCatalogEndpointIntegrationTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test @TestsNotMeantForZowe public void whenDiscoveryClientApiDoc_thenResponseOK() throws Exception { final HttpResponse response = getResponse(GET_DISCOVERABLE_CLIENT_API_DOC_ENDPOINT, HttpStatus.SC_OK); // When final String jsonResponse = EntityUtils.toString(response.getEntity()); String apiCatalogSwagger = "\n**************************\n" + "Integration Test: Discoverable Client Swagger" + "\n**************************\n" + jsonResponse + "\n**************************\n"; DocumentContext jsonContext = JsonPath.parse(jsonResponse); LinkedHashMap swaggerInfo = jsonContext.read("$.info"); String swaggerHost = jsonContext.read("$.host"); String swaggerBasePath = jsonContext.read("$.basePath"); LinkedHashMap paths = jsonContext.read("$.paths"); LinkedHashMap definitions = jsonContext.read("$.definitions"); LinkedHashMap externalDoc = jsonContext.read("$.externalDocs"); // Then assertTrue(apiCatalogSwagger, swaggerInfo.get("description").toString().contains("API")); assertEquals(apiCatalogSwagger, baseHost, swaggerHost); assertEquals(apiCatalogSwagger, "/api/v1/discoverableclient", swaggerBasePath); assertEquals(apiCatalogSwagger, "External documentation", externalDoc.get("description")); assertFalse(apiCatalogSwagger, paths.isEmpty()); assertNotNull(apiCatalogSwagger, paths.get("/greeting")); assertFalse(apiCatalogSwagger, definitions.isEmpty()); assertNotNull(apiCatalogSwagger, definitions.get("ApiMessage")); assertNotNull(apiCatalogSwagger, definitions.get("ApiMessageView")); assertNotNull(apiCatalogSwagger, definitions.get("Greeting")); assertNotNull(apiCatalogSwagger, definitions.get("Pet")); assertNotNull(apiCatalogSwagger, definitions.get("RedirectLocation")); }
Example 16
Source File: ApiCatalogEndpointIntegrationTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void whenCatalogApiDoc_thenResponseOK() throws Exception { final HttpResponse response = getResponse(GET_API_CATALOG_API_DOC_ENDPOINT, HttpStatus.SC_OK); // When final String jsonResponse = EntityUtils.toString(response.getEntity()); String apiCatalogSwagger = "\n**************************\n" + "Integration Test: API Catalog Swagger" + "\n**************************\n" + jsonResponse + "\n**************************\n"; DocumentContext jsonContext = JsonPath.parse(jsonResponse); String swaggerHost = jsonContext.read("$.host"); String swaggerBasePath = jsonContext.read("$.basePath"); LinkedHashMap paths = jsonContext.read("$.paths"); LinkedHashMap definitions = jsonContext.read("$.definitions"); // Then assertFalse(apiCatalogSwagger, paths.isEmpty()); assertFalse(apiCatalogSwagger, definitions.isEmpty()); assertEquals(apiCatalogSwagger, baseHost, swaggerHost); assertEquals(apiCatalogSwagger, "/api/v1/apicatalog", swaggerBasePath); assertNull(apiCatalogSwagger, paths.get("/status/updates")); assertNotNull(apiCatalogSwagger, paths.get("/containers/{id}")); assertNotNull(apiCatalogSwagger, paths.get("/containers")); assertNotNull(apiCatalogSwagger, paths.get("/apidoc/{serviceId}/{apiVersion}")); assertNotNull(apiCatalogSwagger, definitions.get("APIContainer")); assertNotNull(apiCatalogSwagger, definitions.get("APIService")); assertNotNull(apiCatalogSwagger, definitions.get("TimeZone")); }
Example 17
Source File: UserGenerationTest.java From credhub with Apache License 2.0 | 5 votes |
@Test public void whenGivenAUsernameAndPasswordParameters_usesUsernameAndGeneratesPassword() throws Exception { final MockHttpServletRequestBuilder post = post("/api/v1/data") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) .content("{" + "\"name\": \"" + credentialName1 + "\"," + "\"type\": \"user\"," + "\"value\": {" + "\"username\": \"test-username\"" + "}," + "\"parameters\": {" + "\"length\": 40," + "\"exclude_upper\": true," + "\"exclude_lower\": true," + "\"exclude_number\": false," + "\"include_special\": false" + "}" + "}" ); final MockHttpServletResponse response = this.mockMvc.perform(post).andExpect(status() .isOk()).andReturn().getResponse(); final DocumentContext parsedResponse = JsonPath.parse(response.getContentAsString()); final String password = parsedResponse.read("$.value.password"); assertThat(password.length(), equalTo(40)); assertThat(isDigits(password), equalTo(true)); final String username = parsedResponse.read("$.value.username"); assertThat(username, equalTo("test-username")); }
Example 18
Source File: JsonPathTest.java From java-master with Apache License 2.0 | 5 votes |
@Test public void test() throws Exception { File file = ResourceUtils.getFile("classpath:book.json"); DocumentContext documentContext = JsonPath.parse(file); Object object = documentContext.read("$"); System.out.println(object); object = documentContext.read("$.store.book[*].author"); System.out.println(object); object = documentContext.read("$..author"); System.out.println(object); object = documentContext.read("$.store.*"); System.out.println(object); object = documentContext.read("$.store..price"); System.out.println(object); object = documentContext.read("$..book[2]"); System.out.println(object); object = documentContext.read("$..book[-1:]"); System.out.println(object); object = documentContext.read("$..book[0,1]"); System.out.println(object); object = documentContext.read("$..book[?(@.isbn)]"); System.out.println(object); object = documentContext.read("$..book[?(@.price<10)]"); System.out.println(object); }
Example 19
Source File: Script.java From karate with MIT License | 4 votes |
public static void evalJsonEmbeddedExpressions(DocumentContext doc, ScenarioContext context) { Object o = doc.read("$"); evalJsonEmbeddedExpressions("$", o, context, doc); }
Example 20
Source File: ParametersUtils.java From conductor with Apache License 2.0 | 4 votes |
private Object replaceVariables(String paramString, DocumentContext documentContext, String taskId) { String[] values = paramString.split("(?=\\$\\{)|(?<=\\})"); Object[] convertedValues = new Object[values.length]; for (int i = 0; i < values.length; i++) { convertedValues[i] = values[i]; if (values !=null && values[i].startsWith("${") && values[i].endsWith("}")) { String paramPath = values[i].substring(2, values[i].length() - 1); if (EnvUtils.isEnvironmentVariable(paramPath)) { String sysValue = EnvUtils.getSystemParametersValue(paramPath, taskId); if (sysValue != null) { convertedValues[i] = sysValue; } } else { try { convertedValues[i] = documentContext.read(paramPath); }catch (Exception e) { logger.warn("Error reading documentContext for paramPath: {}. Exception: {}", paramPath, e); convertedValues[i] = null; } } } } Object retObj = convertedValues[0]; // If the parameter String was "v1 v2 v3" then make sure to stitch it back if (convertedValues.length > 1) { for (int i = 0; i < convertedValues.length; i++) { Object val = convertedValues[i]; if (val == null) { val = ""; } if (i == 0) { retObj = val; } else { retObj = retObj + "" + val.toString(); } } } return retObj; }