I have a Problem with parsing a JSON Object. I get the JSON Object from uri. I need the number 13 in the string for the next task. Does anybody know, how it is possible to get only the number from this JSON Object?
- name: GET JOB INFORMATION
uri:
url: "http://******"
method: GET
headers:
Accept: 'application/json'
Content-Type: 'application/json'
Authorization: 'Session {{ xxx.json.token }}'
register: result_job
- name: Output_1
debug:
msg: "{{ result_job.json.affectedResources }}"
- name: Output_2
debug:
msg: "{{ result_job.json.affectedResources.split('/')[0] | last }}"
When ansible execute the Task "Output_2" i got an Error:
{"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'split'\n\nThe error appears to have been in
The Output of the Task "Output_1" is this:
"msg": [
"/Manager/tes/objects/bew/13"
]
And the JSON Object look like this:
"msg": {
"affectedResources": [
"/Manager/tes/objects/bew/13"
],
"completedTime": "2022-03-16T..."
"createdTime": "2022...."
}
Thank you!
CodePudding user response:
Here's a script that works as long as two conditions are true:
- In the string ("/Manager/tes/objects/bew/13" in your case), there is only one number enclosed in '/'.
- The number enclosed in '/' (for example, '/13/') is an integer.
Your JSON Object (called json_object
in the script):
"msg": {
"affectedResources": [
"/Manager/tes/objects/bew/13"
],
"completedTime": "2022-03-16T..."
"createdTime": "2022...."
}
Here's the script.
# Navigate to the appropriate element in the JSON object
string = json_object["msg"]["affectedResources"][0]
for item in string.split('/'): # iterate on items between '/'
try:
return_val = int(item) # if the item is an integer
break # quit and keep that value
except:
return_val = None # or other default value
continue
# Result
print(return_val, type(return_val)) >>> 13, <class 'int'>
CodePudding user response:
Given the data
result_job:
json:
affectedResources:
- /Manager/tes/objects/bew/13
completedTime: 2022-03-16T...
createdTime: 2022....
You can see the attribute affectedResources is a list. You say that you "need the number 13 in the string"
. In this case, let's take the first element from the list
"{{ result_job.json.affectedResources.0 }}"
gives the string
/Manager/tes/objects/bew/13
Now, you can split the string and get the last item either by index
"{{ result_job.json.affectedResources.0.split('/').[-1] }}"
, or by the filter
"{{ result_job.json.affectedResources.0.split('/')|last }}"
Both give the same result
'13'