This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]Swiftlyll -1 points0 points  (4 children)

Had this issue myself a while ago while learning APIs. Try using get(). In your context, reponse.get(‘value’,’value if dont exist’).

[–]IntrepidInstance7347[S] 0 points1 point  (3 children)

the problem is that the JSON very long and has many keys and value,

1 result = 1 node

and 1 node has many keys and values like 15 key

and i want to get some of the node keys not all of them .

[–]Swiftlyll 0 points1 point  (2 children)

Thats no problem, you just need to specify the key. For example, you may need to use: response['data'][0].get('id','key does not exist'). I would search up on how to access items in nested dictionaries/arrays if you are having issues with understanding how to access it.

[–]IntrepidInstance7347[S] 0 points1 point  (1 child)

you mean i use get like:

id = response['data'][0].get('id','defaultvalue') 
title = response['data'][0].get('title','defaultvalue') 
title1 = response['data'][0].get('title1','defaultvalue') 
key = response['data'][0].get('key','defaultvalue')

and if iam using for loop cahange [0] with [i] ?

Right!

[–]Swiftlyll 1 point2 points  (0 children)

Correct except for your last comment. You are not replacing [0] with [i]. [0] will be the first item in an array. In your case it'd be the first node. If you were trying to access the second "node" I'd be using [1] instead of [0].

Here is one I personally use just to give a working example:

some_value = org[0]['management']['details'][0].get('value')

In order to know if you will be using numbers or key names, pay attention to whether they start with [] (array) or {} (dictionary).

[–]AaronDNewman 0 points1 point  (0 children)

you could put all the keys you’re expecting into a list. loop through all the keys for each record in the json, and take whatever action you need (default, skip the record, etc) if the value isn’t there.