Accessing object elements in list - json

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"];

Related

Pass list of integers as parameters to Ember transitionTo()?

I'm trying to pass a list of integers (of the form [1,5]) as params in transitionTo in Ember 3.14. I've verified that the list can be read within this function:
afterModel() {
this.transitionTo('newRoute', this.modelFor('lastLevel').list);
},
But I always get this error:
Cannot read property '0' of undefined TypeError: Cannot read property '0' of undefined
How should I transform the list so it will pass into transitionTo()?
I found the pretty simple solution. I had to join the list into a string:
this.transitionTo('newRoute', this.modelFor('lastLevel').list.join(',');

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.

com.jayway.jsonpath.JsonPath cannot find key

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.

How to print an object as JSON to console in Angular2?

I'm using a service to load my form data into an array in my angular2 app.
The data is stored like this:
arr = []
arr.push({title:name})
When I do a console.log(arr), it is shown as Object. What I need is to see it
as [ { 'title':name } ]. How can I achieve that?
you may use below,
JSON.stringify({ data: arr}, null, 4);
this will nicely format your data with indentation.
To print out readable information. You can use console.table() which is much easier to read than JSON:
console.table(data);
This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.
It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table
Example:
first convert your JSON string to Object using .parse() method and then you can print it in console using console.table('parsed sring goes here').
e.g.
const data = JSON.parse(jsonString);
console.table(data);
Please try using the JSON Pipe operator in the HTML file. As the JSON info was needed only for debugging purposes, this method was suitable for me. Sample given below:
<p>{{arr | json}}</p>
You could log each element of the array separately
arr.forEach(function(e){console.log(e)});
Since your array has just one element, this is the same as logging {'title':name}
you can print any object
console.log(this.anyObject);
when you write
console.log('any object' + this.anyObject);
this will print
any object [object Object]

Trying to get a simple loop of JSON passed to POST - Python

I have a WS using Flask/python 2.7. I have 1 JSON object passed to the WS. I have been successful in capturing the object and returning the whole JSON.
I have looked all over for examples (many use print of test dataset in python) and have tried json.dumps, json.loads, json.dump, json.load, for loops, etc.
What I would like to do seems simple and I know it is me, but I get errors no matter what I try. I am trying to parse the JSON, put the values in to variables, and do "stuff".
This works:
#app.route('/v1/test', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'application/json':
return "JSON Message: " + json.dumps(request.json, separators=(',',':'))
else:
return "415 Unsupported Media Type"
This does not (and many variations of this using different things):
jsonobject = json.dumps(request.json)
pstring = json.loads(jsonobject)
for key, value in pstring.iteritems():
return value
What I want to do (pseudo code):
for each JSON
get the name value pairs in to a place where I can do something like this (which was done on a flat file)
input_data = pd.read_csv(sio, delimiter=',', names=columns)
probs = model.predict_proba(input_data)
I am sure I didn't make this as clear as I could but it is a challenge because I get errors like below (examples -- not all at once of course) with all the different things I try:
AttributeError: 'dict' object has no attribute 'translate'
TypeError: 'dict' object is not callable
AttributeError: 'str' object has no attribute 'iteritems'
So after all that, what is the right way to do this?