Java Code Examples for com.jayway.jsonpath.JsonPath#parse()

The following examples show how to use com.jayway.jsonpath.JsonPath#parse() . 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: JsonArrayNodeTest.java    From JsonTemplate with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("convert an array to a json node")
void testOfArray() {
    Object[] objects = new Object[] {
        "string", 123, 123f, true, null
    };

    JsonArrayNode jsonNode = JsonArrayNode.of(objects);
    String json = jsonNode.compactString();
    System.out.println(json);

    DocumentContext document = JsonPath.parse(json);
    assertThat(document.read("$[0]", String.class), is("string"));
    assertThat(document.read("$[1]", Integer.class), is(123));
    assertThat(document.read("$[2]", Float.class), is(123f));
    assertThat(document.read("$[3]", Boolean.class), is(true));
    assertThat(document.read("$[4]"), is(nullValue()));
}
 
Example 2
Source File: GenerateModeTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void generatingACredential_whenConvergeIsSet_andTheCredentialDoesNotExist_createsTheCredential() throws Exception {
    final MockHttpServletRequestBuilder postRequest = post("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON_UTF8)
            .content("{" +
                    "\"type\":\"password\"," +
                    "\"name\":\"" + CREDENTIAL_NAME + "\"," +
                    "\"mode\": \"converge\"," +
                    "\"parameters\":{" +
                    "\"length\":30" +
                    "}" +
                    "}");

    final DocumentContext response = JsonPath.parse(mockMvc.perform(postRequest).andExpect(status().isOk())
            .andDo(print())
            .andReturn()
            .getResponse()
            .getContentAsString());

    final String versionId = response.read("$.id").toString();
    assertThat(versionId, is(notNullValue()));
}
 
Example 3
Source File: ScriptTest.java    From karate with MIT License 6 votes vote down vote up
@Test
public void testMatchAllJsonPath() {
    DocumentContext doc = JsonPath.parse("{ foo: [{bar: 1, baz: 'a'}, {bar: 2, baz: 'b'}, {bar:3, baz: 'c'}]}");
    ScenarioContext ctx = getContext();
    ctx.vars.put("myJson", doc);
    ScriptValue myJson = ctx.vars.get("myJson");
    assertTrue(Script.matchJsonOrObject(MatchType.EQUALS, myJson, "$.foo", "[{bar: 1, baz: 'a'}, {bar: 2, baz: 'b'}, {bar:3, baz: 'c'}]", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.CONTAINS, myJson, "$.foo", "[{bar: 1, baz: 'a'}, {bar: 2, baz: 'b'}, {bar:3, baz: 'c'}]", ctx).pass);
    assertFalse(Script.matchJsonOrObject(MatchType.NOT_CONTAINS, myJson, "$.foo", "[{bar: 1, baz: 'a'}]", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.NOT_CONTAINS, myJson, "$.foo", "[{bar: 9, baz: 'z'}, {bar: 99, baz: 'zz'}]", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.CONTAINS_ONLY, myJson, "$.foo", "[{bar: 1, baz: 'a'}, {bar: 2, baz: 'b'}, {bar:3, baz: 'c'}]", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.CONTAINS_ANY, myJson, "$.foo", "[{bar: 9, baz: 'z'}, {bar: 2, baz: 'b'}]", ctx).pass);
    // shuffle
    assertTrue(Script.matchJsonOrObject(MatchType.CONTAINS_ONLY, myJson, "$.foo", "[{bar: 2, baz: 'b'}, {bar:3, baz: 'c'}, {bar: 1, baz: 'a'}]", ctx).pass);
    assertFalse(Script.matchJsonOrObject(MatchType.CONTAINS_ONLY, myJson, "$.foo", "[{bar: 1, baz: 'a'}, {bar: 2, baz: 'b'}]", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.EACH_EQUALS, myJson, "$.foo", "{bar:'#number', baz:'#string'}", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.EACH_CONTAINS, myJson, "$.foo", "{bar:'#number'}", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.EACH_CONTAINS, myJson, "$.foo", "{baz:'#string'}", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.EACH_NOT_CONTAINS, myJson, "$.foo", "{baz:'z'}", ctx).pass);
    assertFalse(Script.matchJsonOrObject(MatchType.EACH_NOT_CONTAINS, myJson, "$.foo", "{baz:'a'}", ctx).pass);
    assertFalse(Script.matchJsonOrObject(MatchType.EACH_EQUALS, myJson, "$.foo", "{bar:'#? _ < 3',  baz:'#string'}", ctx).pass);
}
 
Example 4
Source File: GreetingApiIntegrationTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@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 5
Source File: ParametersUtils.java    From conductor with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> replace(Map<String, Object> input, Object json) {
    Object doc;
    if (json instanceof String) {
        doc = JsonPath.parse(json.toString());
    } else {
        doc = json;
    }
    Configuration option = Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS);
    DocumentContext documentContext = JsonPath.parse(doc, option);
    return replace(input, documentContext, null);
}
 
Example 6
Source File: OperationIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() {
    String jsonpathCreatorNamePath = "$['tool']['jsonpath']['creator']['name']";
    String jsonpathCreatorLocationPath = "$['tool']['jsonpath']['creator']['location'][*]";

    DocumentContext jsonContext = JsonPath.parse(jsonDataSourceString);
    String jsonpathCreatorName = jsonContext.read(jsonpathCreatorNamePath);
    List<String> jsonpathCreatorLocation = jsonContext.read(jsonpathCreatorLocationPath);

    assertEquals("Jayway Inc.", jsonpathCreatorName);
    assertThat(jsonpathCreatorLocation.toString(), containsString("Malmo"));
    assertThat(jsonpathCreatorLocation.toString(), containsString("San Francisco"));
    assertThat(jsonpathCreatorLocation.toString(), containsString("Helsingborg"));
}
 
Example 7
Source File: UploadStepdefs.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Then("^\"([^\"]*)\" should be able to retrieve the content$")
public void contentShouldBeRetrievable(String username) throws Exception {
    AccessToken accessToken = userStepdefs.authenticate(username);
    DocumentContext jsonPath = JsonPath.parse(response.getEntity().getContent());
    Request request = Request.Get(baseUri(mainStepdefs.jmapServer).setPath("/download/" + jsonPath.<String>read("blobId")).build());
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.asString());
    }
    response = request.execute().returnResponse();
    httpAuthorizedStatus();
}
 
Example 8
Source File: ServiceIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@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 9
Source File: ApiMediationLayerStartupChecker.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private boolean successfulResponse() {
    try {
        HttpGet request = HttpRequestUtils.getRequest("/application/health");
        final HttpResponse response = HttpClientUtils.client().execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            log.warn("Unexpected HTTP status code: {}", response.getStatusLine().getStatusCode());
            return false;
        }
        final String jsonResponse = EntityUtils.toString(response.getEntity());
        log.debug("URI: {}, JsonResponse is {}", request.getURI().toString(), jsonResponse);

        DocumentContext documentContext = JsonPath.parse(jsonResponse);

        boolean isGatewayUp = documentContext.read("$.status").equals("UP");
        log.debug("Gateway is {}", isGatewayUp ? "UP" : "DOWN");

        boolean isAllInstancesUp = allInstancesUp(documentContext);
        log.debug("All instances are {}", isAllInstancesUp ? "UP" : "DOWN");

        boolean isTestApplicationUp = testApplicationUp(documentContext);
        log.debug("Discoverableclient is {}", isTestApplicationUp ? "UP" : "DOWN");

        return isGatewayUp && isAllInstancesUp && isTestApplicationUp;
    } catch (IOException | PathNotFoundException e) {
        log.warn("Check failed: {}", e.getMessage());
    }
    return false;
}
 
Example 10
Source File: JsonPathTest.java    From java-master with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: Script.java    From karate with MIT License 5 votes vote down vote up
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 12
Source File: ApiCatalogEndpointIntegrationTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void whenGetContainerStatuses_thenResponseWithAtLeastOneUp() throws Exception {
    final HttpResponse response = getResponse(GET_ALL_CONTAINERS_ENDPOINT, HttpStatus.SC_OK);

    // When
    final String jsonResponse = EntityUtils.toString(response.getEntity());
    DocumentContext jsonContext = JsonPath.parse(jsonResponse);
    JSONArray containerTitles = jsonContext.read("$.[*].title");
    JSONArray containerStatus = jsonContext.read("$.[*].status");

    // Then
    assertTrue("Tile title did not match: API Mediation Layer API", containerTitles.contains("API Mediation Layer API"));
    assertTrue(containerStatus.contains("UP"));
}
 
Example 13
Source File: Verify.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static void verifyResourceDescriptors(File actualPath, File expectedPath, boolean strict) throws IOException, ParseException {
    String actualText = readFile(actualPath);
    String expectedText = readFile(expectedPath);


    JsonTextMessageValidator validator = new JsonTextMessageValidator();
    validator.setStrict(strict);

    DocumentContext actualContext = JsonPath.parse(actualText);
    validator.validateJson(newMessage(actualText),
                           newMessage(expectedText),
                           new JsonMessageValidationContext(),
                           createTestContext(),
                           actualContext);
}
 
Example 14
Source File: ScriptTest.java    From karate with MIT License 5 votes vote down vote up
@Test
public void testMatchJsonPath() {
    DocumentContext doc = JsonPath.parse("{ foo: 'bar', baz: { ban: [1, 2, 3]} }");
    ScenarioContext ctx = getContext();
    ctx.vars.put("myJson", doc);
    ScriptValue myJson = ctx.vars.get("myJson");
    assertTrue(Script.matchJsonOrObject(MatchType.EQUALS, myJson, "$.foo", "'bar'", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.EQUALS, myJson, "$.baz", "{ ban: [1, 2, 3]} }", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.EQUALS, myJson, "$.baz.ban[1]", "2", ctx).pass);
    assertTrue(Script.matchJsonOrObject(MatchType.EQUALS, myJson, "$.baz", "{ ban: [1, '#ignore', 3]} }", ctx).pass);
}
 
Example 15
Source File: GenerateModeTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void generatingACredential_inNoOverwriteMode_doesNotUpdateTheCredential() throws Exception {
    MockHttpServletRequestBuilder postRequest = post("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            .content("{" +
                    "\"type\":\"password\"," +
                    "\"name\":\"" + CREDENTIAL_NAME + "\"" +
                    "}");

    DocumentContext response = JsonPath.parse(mockMvc.perform(postRequest).andExpect(status().isOk())
            .andDo(print())
            .andReturn()
            .getResponse()
            .getContentAsString());

    final String versionId = response.read("$.id").toString();

    postRequest = post("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            .content("{" +
                    "\"type\":\"password\"," +
                    "\"name\":\"" + CREDENTIAL_NAME + "\"," +
                    "\"mode\": \"no-overwrite\"" +
                    "}");

    response = JsonPath.parse(mockMvc.perform(postRequest).andExpect(status().isOk())
            .andDo(print())
            .andReturn()
            .getResponse()
            .getContentAsString());

    assertThat(response.read("$.id").toString(), is(equalTo(versionId)));
}
 
Example 16
Source File: JsonService.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
private void parseJsonForInconsistencies(String normalizedJson) {
    JsonProvider provider = new GsonJsonProvider();
    Configuration configuration = Configuration.builder().jsonProvider(provider).build();
    JsonPath.parse(normalizedJson, configuration);       //throws an exception at runtime if the json is malformed
}
 
Example 17
Source File: JsonBodyVerificationBuilder.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
Object addJsonResponseBodyCheck(BlockBuilder bb, Object convertedResponseBody,
		BodyMatchers bodyMatchers, String responseString,
		boolean shouldCommentOutBDDBlocks) {
	appendJsonPath(bb, responseString);
	DocumentContext parsedRequestBody = null;
	boolean dontParseStrings = convertedResponseBody instanceof Map;
	Closure parsingClosure = dontParseStrings ? Closure.IDENTITY
			: MapConverter.JSON_PARSING_CLOSURE;
	if (hasRequestBody()) {
		Object testSideRequestBody = MapConverter
				.getTestSideValues(contract.getRequest().getBody(), parsingClosure);
		parsedRequestBody = JsonPath.parse(testSideRequestBody);
		if (convertedResponseBody instanceof String
				&& !textContainsJsonPathTemplate(convertedResponseBody.toString())) {
			convertedResponseBody = templateProcessor.transform(contract.getRequest(),
					convertedResponseBody.toString());
		}
	}
	Object copiedBody = cloneBody(convertedResponseBody);
	convertedResponseBody = JsonToJsonPathsConverter
			.removeMatchingJsonPaths(convertedResponseBody, bodyMatchers);
	// remove quotes from fromRequest objects before picking json paths
	TestSideRequestTemplateModel templateModel = hasRequestBody()
			? TestSideRequestTemplateModel.from(contract.getRequest()) : null;
	convertedResponseBody = MapConverter.transformValues(convertedResponseBody,
			returnReferencedEntries(templateModel), parsingClosure);
	JsonPaths jsonPaths = new JsonToJsonPathsConverter(assertJsonSize)
			.transformToJsonPathWithTestsSideValues(convertedResponseBody,
					parsingClosure);
	DocumentContext finalParsedRequestBody = parsedRequestBody;
	jsonPaths.forEach(it -> {
		String method = it.method();
		method = processIfTemplateIsPresent(method, finalParsedRequestBody);
		String postProcessedMethod = templateProcessor.containsJsonPathTemplateEntry(
				method) ? method : postProcessJsonPathCall.apply(method);
		bb.addLine("assertThatJson(parsedJson)" + postProcessedMethod);
		addColonIfRequired(lineSuffix, bb);
	});
	doBodyMatchingIfPresent(bodyMatchers, bb, copiedBody, shouldCommentOutBDDBlocks);
	return convertedResponseBody;
}
 
Example 18
Source File: PostmanUtils.java    From karate with MIT License 4 votes vote down vote up
public static List<PostmanItem> readPostmanJson(String json) {
    DocumentContext doc = JsonPath.parse(json);
    List<Map<String, Object>> list = (List) doc.read("$.item");
    return readPostmanItems(null, list);
}
 
Example 19
Source File: JsonUtils.java    From karate with MIT License 4 votes vote down vote up
public static DocumentContext toJsonDoc(String raw) {
    return JsonPath.parse(raw);
}
 
Example 20
Source File: JsonUtils.java    From mangooio with Apache License 2.0 2 votes vote down vote up
/**
 * Converts a given Json string to an JSONPath ReadContext
 * 
 * @param json The json string to convert
 * @return JSPNPath read context
 */
public static ReadContext fromJson(String json) {
    Objects.requireNonNull(json, Required.JSON.toString());
    
    return JsonPath.parse(json);
}