EzDevInfo.com

JsonPath

Java JsonPath implementation json-path - Java JsonPath implementation - Google Project Hosting

JSONPath or other XPath like utility for JSON/Javascript; or Jquery JSON

I have been looking at JSONPath and though it seems pretty well done, I wonder if anyone has worked with it and can comment on its usability, or can recommend alternatives? What would be really slick is if there was a plugin for JQuery that did something like this. I have been searching the plugins and coming up empty handed. Anyway, before I spend time getting to know JSONPath (which has some aspects I am not keen on), or before I reinvent wheels, I thought I'd see if anyone had an angle on this...

To give you an idea what I mean, imagine this Javascript object:

var Characters=[
        {
            id: "CuriousGeorge",
            species:"Monkey",
            mood: "curious",
            appendage: [
                { 
                    type: "hand",
                    side: "left",
                    holding: [ 
                        { id: "Banana" } 
                    ]
                },
                { 
                    type: "hand",
                    side: "right",
                    holding: []
                }, 
                { 
                    type: "foot",
                    side: "left",
                    holding: []
                },
                { 
                    type: "foot",
                    side: "right",
                    holding: [ 
                        { id: "YellowHat" },
                        { id: "Keys" }
                    ]
                }
            ]
        },
        {
            id: "ManInYellowHat",
            species: "Human",
            mood: "angry",
            //...ok, you get it...
        }
    ]

Wouldn't it be great to get to of some of the deeper objects by something like Jquery selectors?

var banana=SomeUtility("Characters holding #Banana").get(0);
var leftHands=SomeUtility("Characters appendage[type=hand][side=left]").get();

(This may qualify for worlds corniest code example, but hey, my kids just watched this. And I can't use real example because of NDA...)

...And, to make it more interesting, if I were to create such a thing, would anyone use it?


Source: (StackOverflow)

SpringMVC/ mockMVC/ jsonpath compare list of strings

I am currently writing some unit tests for a Spring MVC project. As the returned media type is JSON, I try to use jsonPath to check if the correct values are returned.

The trouble I have is to verify if a list of strings contains the correct (and only the correct) values.

My Plan was:

  1. Check that the list has the correct length
  2. For each element that's supposed to be returned, check whether it's in the list

sadly, none of these things seem to work.

Here's the relevant part of my code:

Collection<AuthorityRole> correctRoles = magicDataSource.getRoles();

ResultActions actions = this.mockMvc.perform(get("/accounts/current/roles").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()) // works
.andExpect(jsonPath("$.data.roles").isArray()) // works
.andExpect(jsonPath("$.data.roles.length").value(correctRoles.size())); // doesn't work

for (AuthorityRole role : correctRoles) // doesn't work
  actions.andExpect(jsonPath("$.data.roles[?(@=='%s')]", role.toString()).exists());

Only the first two "expectations" (isOk & isArray) are working. The other ones (for length and content) I can twist and turn however I want, they're not giving me any useful result.

Any suggestions?


Source: (StackOverflow)

Advertisements

How to filter by string in JSONPath?

I have a JSON response from the Facebook API that looks like this:

{
  "data": [
     {
       "name": "Barack Obama", 
       "category": "Politician", 
       "id": "6815841748"
     }, 
     {
       "name": "Barack Obama's Dead Fly", 
       "category": "Public figure", 
       "id": "92943557739"
     }]
 }

I want to apply JSONPath to it to only return results with a category of "Politician". From what I've read, it appears that I need to do:

$.data[?(@.category=='Politician')]

but according to the testing tool I found, this doesn't work. I found another question which suggests that I should use "eq" instead of "==", but that doesn't work either. What am I getting wrong here?


Source: (StackOverflow)

Hamcrest with MockMvc: check that key exists but value may be null

I'm doing some tests with MockMvc, and I want to validate the structure of a JSON response. Specifically, I want to make sure that the key to an attribute exists, and that the value is of a certain type or null.

{
   "keyToNull": null,  # This may be null, or a String
   "keyToString": "some value"
}

The following works for me, but I'm wondering if there's a way to combine each group of two expectations into a single line, as I have a lot of attributes to check:

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.*;

.andExpect(jsonPath("$").value(hasKey("keyToNull")))
.andExpect(jsonPath("$.keyToNull").value(
                  anyOf(any(String.class), nullValue(String.class))))

.andExpect(jsonPath("$").value(hasKey("keyToString")))
.andExpect(jsonPath("$.keyToString").value(
                  anyOf(any(String.class), nullValue(String.class))))

The hasKey() is necessary because the other assertion by itself passes since nonexistent keys in MockMvc's implementation map to null:

.andExpect(jsonPath("$.notAKey").value(
                  anyOf(any(String.class), nullValue(String.class)))) // ok

jsonPath().exists() also doesn't work, because internally it compares the value against null.

I've considered making a separate method like this:

private static <T> void assertNullableAttr(ResultActions res, String jsonPath, Class<T> type) throws Exception {
    int split = jsonPath.lastIndexOf('.');
    String prefix = jsonPath.substring(0, split), key = jsonPath.substring(split+1);

    res.andExpect(jsonPath(prefix).value(hasKey(key)))
        .andExpect(jsonPath(jsonPath).value(anyOf(any(type), nullValue(type))));
    }

But then it forces me to split my code in an unnatural way:

ResultActions res = mockMvc.perform(get("/api"))
    // these attributes must not be null
    .andExpect(jsonPath("$.someInfo").value(hasSize(2)))
        .andExpect(jsonPath("$.someInfo[0].info1").value(any(String.class)))
        .andExpect(jsonPath("$.someInfo[0].info2").value(any(String.class)))
    .andExpect(jsonPath("$.addlInfo").value(hasSize(2)))
        .andExpect(jsonPath("$.addlInfo[0].info1").value(any(String.class)))
        .andExpect(jsonPath("$.addlInfo[0].info2").value(any(String.class)));

// these attributes may be null
assertNullableAttr(res, "$.someInfo[0].info3", String.class);
assertNullableAttr(res, "$.someInfo[0].info4", String.class);

assertNullableAttr(res, "$.addlInfo[0].info3", String.class);
assertNullableAttr(res, "$.addlInfo[0].info4", String.class);

Is there any clever Hamcrest Matcher I could apply to a single json path per attribute?


Source: (StackOverflow)

Testing with spring-test-mvc jsonpath returns null

I am using Spring's "spring-test-mvc" library to test web controllers. I have a very simple controller that returns a JSON array. Then in my test I have:

@Test
public void shouldGetAllUsersAsJson() throws Exception {
    mockMvc.perform(get("/v1/users").accept(MediaType.APPLICATION_JSON))
            .andExpect(content().mimeType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("fName").exists());
}

The above test returns:

java.lang.AssertionError: No value for JSON path: fName

To quickly check what I actually get I ran the below test:

@Test
public void shouldPrintResults() throws Exception {
    mockMvc.perform(get("/v1/users").accept(MediaType.APPLICATION_JSON))
            .andDo(print());
}

And it returns the correct JSON array in the body of MockHttpServletResponse

I'm not sure why jsonPath is not able to see fName in the JSON array.


Source: (StackOverflow)

In Python, using jsonpath-rw to get values for specific attribute (json/dict)

Here's my json:

{
   'test': [
        { "id": "1", "description": "Test 1" },
        { "id": "2", "description": "Test 2" }
    ]
}

I'm trying to get the value for id where description is "Test 1".

I found the following example on the JsonPath page:

$..book[?(@.price<10)]

When trying to parse the following jsonxpath expression:

parse('$..test[?(@.description="Test 1")].id')

I get the following error:

jsonpath_rw.lexer.JsonPathLexerError: Error on line 1, col 7: Unexpected character: ?

What am I doing wrong? Alternatively, is there a better way to do this?


Source: (StackOverflow)

How to list object key names with jsonpath?

I am using nodejs with jsonpath. I have this json structure:

{
  things:{
    books: [
      {name: "book1"},
      {name: "book2"},
      {name: "book3"},
      {name: "book4"},
    ],
    movies: [
      {name: "movie1"},
      {name: "movie2"},
      {name: "movie3"},
      {name: "movie4"},
    ]
  }
}

I would like to know the jsonpath expression that returns an array with the key names of the things object. That would be:

["books","movies"]

For now, I am doing this:

Object.keys(jsonpath.eval(jsonStructure,"$.things").pop());

But I don't find it elegant... I should not need to get a copy the whole structure when I only need the key names.


Source: (StackOverflow)

ATLANTBH jmeter-components: JSON Path Assertion

I'm trying to perform a JSON assertion using ATLANTBH jmeter JSON PATH Assertion.
However I cant seem to write a correct expression to get the following fields from the JSON feed posted below:

  1. 123456789
  2. 1009
  3. SOME RANDOM MESSAGE

    {"api": {"status":"Success","callsremaining":36,"version":"x.x.x.x"}
    ,"result":{"errors":{"123456789":{"code":1009,"error":"SOME RANDOM MESSAGE"}}}
    }
    

Has anyone here got any experience using this JMeter plugin?
I know I could use regex and Beanshell to validate but I'd rather use these JSON Path Assertion.

Any help you could provide would be most appreciated.


Source: (StackOverflow)

Handling jsonp in rails 3 controller

I want my controller action to handle jsonp requests from jquery $.getJSON. In my controller action i have the following respond_to block:

respond_to do |format|
  format.html { render json: {:items_by_tag => @tagged_item_list}}
  if params[:callback]
        format.js { render :json => {:items_by_tag => @tagged_item_list}.to_json, :callback => params[:callback] }
  else
        format.json { render json: {:items_by_tag => @tagged_item_list}}
  end
end

But I'm getting SyntaxError:invalid label when i call the url from $.getJSON. My url is of the form http://myservice.com?param1=a&param2=b&callback=?.
What is the problem with my code which is causing jsonp to fail?


Source: (StackOverflow)

How do you reference the root key using JSON Path?

I have data like so:

{"key": {"name":"hi", "size":10}}

"key" is a dynamic value. It isn't fixed. I can access name and size using this JSON Path:

*.name
*.size

How can I get the value of "key" itself with JSON Path? * gives me the entire row of data, and both $ and @ give me "no element found" in my parser.

I'm trying to do this in Pentaho with a JSON Input step.


Source: (StackOverflow)

JSON.NET how to remove nodes

I have a json like the following:

{
  "d": {
    "results": [
      {
        "__metadata": {
        },
        "prop1": "value1",
        "prop2": "value2",
        "__some": "value"
      },
      {
        "__metadata": {
        },
        "prop3": "value1",
        "prop4": "value2",
        "__some": "value"
      },
    ]
  }
}

I just want to transform this JSON into a different JSON. I want to strip out the "_metadata" and "_some" nodes from the JSON. I'm using JSON.NET.


Source: (StackOverflow)

Parse JSON array file with JSONPATH

I want to parse this with JSONPath:

[
  [50.4154134372953,-1.28486558931069,"CLASS B",9,205,0,"UK",431500382,3,4],
  [50.3058858494047,-0.976070494820637,"CLASS B",9,239,0,"UK",2750350,21,2]
]

Can you help with that please?


Source: (StackOverflow)

How to use C# example using JsonPath?

I'm trying to use JsonPath for .NET (http://code.google.com/p/jsonpath/downloads/list) and I'm having trouble finding an example of how to parse a Json string and a JsonPath string and get a result.

Has anyone used this?


Source: (StackOverflow)

count members with jsonpath?

Is it possible to count the number of members using JsonPath?

Using spring mvc test I'm testing a controller that generates

{"foo": "oof", "bar": "rab"}

with

standaloneSetup(new FooController(fooService)).build()
            .perform(get("/something").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(jsonPath("$.foo").value("oof"))
            .andExpect(jsonPath("$.bar").value("rab"));

I'd like to make sure that no other members are present in the generated json. Hopefully by counting them using jsonPath. Is it possible? Alternate solutions are welcome too.


Source: (StackOverflow)

Get field from JsonPath in java [closed]

How to get field from a:b:c:d:f:1.0 property via JsonPath?

"a:b:c:d:f:1.0" : {
    "field" : "field"}

I tried with a:b:c:d:f:1.0.field but returns invalid path.


Source: (StackOverflow)