com.jayway.jsonpath.JsonPath cannot find key - json

I am trying to use com.jayway.jsonpath.JsonPath to read key/values from a JSON string:
String contentAsString = mvcResult.getResponse().getContentAsString();
System.out.println(contentAsString);
Object value = JsonPath.read(contentAsString, "$.key");
But I get the error:
Expected to find an object with property ['key'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
Printing contentAsString gives:
[{"firstName":"N","key":"mykey"}]
Is contentAsString not valid JSON?

The blob that you posted is not a valid JSON Object, however, it IS a valid JSON Array.
To read this using JsonPath, try using this:
Object value = JsonPath.read(contentAsString, "$[0].key");
This will get the value of the key object, from the 0th element of the initial array.

Related

Accessing object elements in list

I get the response of a server:
r = requests.get(my_url)
print(r.text)
json_response = json.loads(r.text)
print(type(json_response))
I am using json.loads() to convert the string into json. However, the response has this format:
[{"element_info":{"data":201863539001,......]
I want to access element_info.data. I tried accessing it with json_response.element_info.data but i got AttributeError: 'list' object has no attribute 'bkdn_elem_info'.
I also tried content = r.read() and i got AttributeError: 'Response' object has no attribute 'read'.
You cannot access the elements of a dictionary in python with '.' operator as in javascript. You have to use the square bracket notation as below to access the elements
json_response[0]["element_info"]["data"]
The type of json_response is list. So, you can iterate on it and access each element in it. Each element is a dictionary. So, you can use the keys:
for each_element in json_response:
print(each_element["element_info"]["data"])
If you are not sure that these keys are available in all elements, you can use the get() method with a default value to avoid errors when the key does not exist. Here, the first operand is the key that you want to read, and the second operand can be used to define a default value:
for each_element in json_response:
print(each_element.get("element_info", {}).get("data", ""))
In access to data from a list, you must specify the element with index first and then get the property of the object
objectOfList =json_response[0];
value = objectOfList["element_info"]["data"];

JSON Object Parse

exercise question screenshot
Not sure what's missing. The other discussion solutions seem too complicated compared to my homework question:
Q:
-The variable str_json has been assigned a string of a JSON object
-Call the parse method, pass it str_json and assign the return value to variable jsonobj
-Assign the property the_city to the variable v_the_city
-Assign the property stateval to the variable v_stateval
var str_json = {'v_the_city':'the_city','v_stateval':'stateval'};
var jsonobj = JSON.parse(str_json);
SyntaxError:
the JSON dataJSON.parse: unexpected character at line 1 column 2 of
SyntaxError: unexpected token: identifier
str_json should be a JSON string, not an object.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned. Read more here, link.
Syntax:
JSON.parse(text[, reviver])
Parameters:
text - The string to parse as JSON. See the JSON object for a description of JSON syntax.
reviver - [Optional] If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.

How to extract value from a nested json array?

i have a json object which contains json data with a key. now i want to extract value from that json object like name, address etc and store them to variables.
controller
json_arr = new JSONArray(j_str);
int count = json_arr.length();
json_o.put("user", json_arr);
j_str contains following data
[{"Bollywood":[{"actor":[{"name":"AA","gender":"Male"},{"name":"BB","gender":"Male"}]}]},{"Hollywood":[{"actor":[{"name":"CC","gender":"Male"},{"name":"DD","gender":"Male"}]}]}]
now it is converted to json object -- json_o ,, putting a key --- "user". now how can get a specific data such as 2nd actor name from hollywood. (i.e value DD). after then store that to a string.
Short answer: Use Jackson to map the json string to a java object, and then extract that value as a variable.
Here is a quick guide on doing this with jackson: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

JSON to a JSON array Cannot deserialize the current JSON object in MVC5

I have the following code to fetch data from Json object
System.Console.WriteLine("Error Create Order: {0} {1}", postOrderResult.StatusCode, postOrderResult.ReasonPhrase);
var orderResults = postOrderResult.Content.ReadAsAsync<List<OrderResult>>().Result;
But its returning error
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ABCS.WebApi.Models.OrderResult]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'Message', line 1, position 11.
Please help
Seems like you are passing a simple JSON object while your data type is expecting for an array of JSON objects.
Try encasing your current JSON data between "[" and "]"

Jettison can not convert json string to json object when there is an element has empty string value

My application is using camel rest (2.15.2) to catch a POST json String and then uses jettison to convert to a JSON Object. It is working fine with normal request.
POST request: {"request"={"lname"="aaa", "fname"="bb"}}
1. String body = exchange.getIn().getBody(String.class);
2. JSONObject obj = new JSONObject(body);
When i debug, variable body = {request={lname=aaa, fname=bb}}.
And line 2 returns a JSONObject. so far so good
if we try to another the request:
{"request"={"lname"=" ", "fname"="aa"}}
then body = {request={lname= , fname=aa}}
line2 returns Exception.
Could you please help me to fix this issue: convert json string which contains element has empty value string to json object.
The above request is acceptable in my scenarios.
Error:
org.codehaus.jettison.json.JSONException: Missing value. at character
15 of {request={lname= , fname=aa}} at
org.codehaus.jettison.json.JSONTokener.syntaxError(JSONTokener.java:463)
at
org.codehaus.jettison.json.JSONTokener.nextValue(JSONTokener.java:356)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:230)
at
org.codehaus.jettison.json.JSONTokener.newJSONObject(JSONTokener.java:412)
at
org.codehaus.jettison.json.JSONTokener.nextValue(JSONTokener.java:327)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:230)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:311)