I have a json that I have via a python request, and I need to check if the "extension" key is equal to "txt", if so give a message.
from requests import get
import json
url = get('http://', auth = ('user', 'password'))
data_JSON = url.json()
for element in json['diffs']:
if element['extension'] == 'txt':
print ("have txt")
The json that returns from the request is this:
{
"fromHash":"***",
"toHash":"BG",
"contextLines":10,
"whitespace":"SHOW",
"diffs":[
{
"source":{
"components":[
"arquivo1.txt"
],
"parent":"",
"name":"arquivo1.txt",
"extension":"txt",
"toString":"arquivo1.txt"
},
....
I want to check the extension key if the value is txt, if yes return a message
Use element['source']['extension'] instead of element['extension'] since extension is a key within element['source'] not element directly.
from requests import get
import json
url = get('http://', auth = ('user', 'password'))
data_JSON = url.json()
for element in data_JSON['diffs']:
if element['source']['extension'] == 'txt':
print('have txt')
There is no need to use a for loop to iterate over "diffs".
Simply use an index such as 0.
Take a look at the following data which represents your JSON structure.
sample_json = {
"diffs":[
{
"source":{
"extension":"txt",
}
}
]
}
It appears, our first key is called diffs which has a list value.
We can easily access the diffs list by using sample_json["diffs"]; This returns a list.
So we index it -> sample_json["diffs"][0]
We get a dictionary (go to source) -> sample_json["diffs"][0]["source"]
Look for the extensions key -> sample_json["diffs"][0]["source"]["extensions"]
I've given you an explanation so that later on in the future you can follow a similar process.
code
sample_json = {
"diffs":[
{
"source":{
"extension":"txt",
}
}
]
}
extension = sample_json["diffs"][0]["source"]["extension"]
if extension == "txt":
print("true")
Related
{ "PrcCfgDetails": [
{
"header_id": "10984299",
"line_id": "1143673632"
},
{
"header_id": "10984299",
"line_id": "1143673633"
}
]
}
I have above response file and I have written next 2 line of code in python. I do see above in response2 but don't know how to write a loop and get the value of header_id and line_id for number of records in response. Can you please help me in writing rest of the code.
response2 = requests.post(OAUTH_ENDPOINT, headers=headers_get, data=python2json)
user_data1 = json.dumps(response2.text)
user_data1 = response2.json()
Will return a dictionary of lists of dictionary. The top level will have one key -- PrcCfgDetails -- accessible with user_data1.get('ProCfgDetails')
I'm working in Python (3.8) and I've successfully called an API gotten it to print the JSON within command line after running the Python file. Now, I want to be able to print a particular list of information (like all of the names from the JSON), and later on save that list as its own set of data, but I'm hitting a block.
Example JSON I'm working with:
{
"data": {
"employees": [
{
"fields": {
"name": "Buddy",
"superheroName": "Syndrome",
"workEmail": "syndrome#example.com",
}
},
{
"fields": {
"name": "Helen Parr",
"superheroName": "Elastigirl",
"workEmail": "elastigirl#example.com",
}
}
]
}
I’ve tried the following so far and I was able to get “data” to print, but anytime I try to print another “layer” and get to say...“employees” or “fields” even, I hit a wall.
url = "my API url"
response = requests.get(url)
if response.status_code != 200:
print('Error with status code {}'.format(response.status_code))
exit()
jsonResponse = response.json()
jsonPretty = json.dumps(jsonResponse, indent=4, sort_keys=True)
jsonDictionary = json.loads(jsonPretty)
keys = jsonDictionary.keys()
for key in jsonDictionary.keys():
print(key)
Ideally, could someone share insight into how I can access the 'name' JSON value and get Python to print it as a list like the following, for example:
Buddy
Helen Parr
JSON files are basically nested dictionaries. jsonDictionary only contains one key and one entry under that key: data and another dictionary with the rest your result respectively.
If you wanted to access the name fields specifically:
employeesDict = jsonDictionary['data']
feildsDictList = employeesDict['employees']
firstFieldsDict = fieldsDictList[0]
secondFieldsDict = fieldsDictList[1]
firstName = firstFieldsDict['name']
secondNAme = secondFieldsDict['name']
You can access it like this (make sure it's already a dictionary):
for i in h['data']['employees']:
print(i['fields']['name'])
This way you can access the names with i['fields']['name']
I am trying to modify a JSON with Python but I can not do it correctly.
I have tried the module that comes with Python by default to deal with JSON but I can not do the next step.
The JSON to modify is this:
{
"uuid":"789ce6ed-ec0f-418b-8fad-6ba64cb8bd70",
"assetTemplate":[
{
"id":14,
"name":"Template-conectividad"
},
{
"id":54,
"name":"Template-discos-agata"
},
{
"id":17,
"name":"Template-servidor-linux"
}
],
"info":null
}
And it should look like this:
{
"uuid":"789ce6ed-ec0f-418b-8fad-6ba64cb8bd70",
"assetTemplate":[
{
"id":54,
"name":"Template-discos-agata"
},
{
"id":17,
"name":"Template-servidor-linux"
},
{
"id":85,
"name":"Template-conectividad-test"
}
],
"info":null
}
This is what I tried to remove the part I do not want but I have the part to insert the new data:
#!/usr/bin/python
import json
# We load JSON to modify
x = '{"uuid":"789ce6ed-ec0f-418b-8fad-6ba64cb8bd70","assetTemplate":[{"id":14,"name":"Template-conectividad"},{"id":54,"name":"Template-discos-agata"},{"id":17,"name":"Template-servidor-linux"}],"info":null}'
y = json.loads(x)
obj = y["assetTemplate"]
# We remove the object that we dont want
for i in range(len(obj)):
if obj[i]['id'] == 14:
del obj[i]
break
print(obj)
# We make output of what has been achieved
x = json.dumps(y)
print(x)
When you load a json, its contents are loaded as dictionaries ({} with contents as key:value) and lists ([]).
That means obj is a normal list - which you already kinda know because you iterate over it.
Because it's a normal list, you can just .append what you want as a dictionary, so:
d={"id":85,"name":"Template-conectividad-test"}
obj.append(d)
I'm getting a JSON data from RESTCONF HTTPS request, using the following code
https_request = 'https://' + host + '/restconf/data/' + operation
headers = {'Content-type': 'application/yang-data+json', 'Accept': 'application/yang-data+json'}
r = requests.get(https_request, auth=(user, password), headers=headers, verify=False)
print r.json()
The data I got is the following:
{
"Cisco-IOS-XE-segment-routing:ipv4": {
"prefixes": [
{
"ipprefix": "1.1.1.1/32",
"index": {
"range-start": 333,
"range": 1
}
}
]
}
}
Basically, I want to return the field's "range-start" value which is 333. I tried the following but it did not work.
for element in r:
id = element['range-start']
print(id)
Is there anyway to get that value?
From Python Console:
>>> import json
... data = json.loads('{"Cisco-IOS-XE-segment-routing:ipv4": {"prefixes": [{"ipprefix": "1.1.1.1/32", "index": {"range-start": 333, "range": 1}}]}}')
... print(data['Cisco-IOS-XE-segment-routing:ipv4']['prefixes'][0]['index']['range-start'])
333
>>>
You need to start at the beginning of the JSON and work your way to the key you want. To do this you need to start at Cisco-IOS-XE-segment-routing:ipv4.
prefixes = r.json()["Cisco-IOS-XE-segment-routing:ipv4"]["prefixes"]
id = prefixes[0]["index"]["range-start"]
If there are multiple prefixes you can loop over them and access each range-start.
Since you are looping over elements, I would suggest this approach using a helper function:
def get_id(element):
prefixes = r.json()["Cisco-IOS-XE-segment-routing:ipv4"]["prefixes"]
id = prefixes[0]["index"]["range-start"]
return id
Then you can do, as in your question:
for element in r:
id = get_id(element)
print(id)
I have the following json object (Say car_details.json):
{
"name":"John",
"age":30,
"cars":
[
{
"car_model": "Mustang",
"car_brand": "Ford"
},
{
"car_model": "cx-5",
"car_brand": "Mazda"
}
}
I want to change the value of car_model from cx-5 to cx-9 through python code.
I am providing the json path to this element, through an external file. The json-path expression is basically represented as a string. Something like this:
'cars[2].car_model'
And the new value is also provided through an external file as a string:
'cx-9'
Now how do I parse through car_details.json using the jsonpath expression, and change its value to the one provided as string, and finally return the modified json object
P.S I want to do this through python code
This is an approach without using json module. Load your data in variable. Then iterate over cars key/values. If you find the key that is the value you are looking for set it to new value.
Also note: you need to close your array block, otherwise your above json is not valid. Generally I use an online json parser to check if my data is valid etc. (may be helpful in future).
data = {
"name":"John",
"age":30,
"cars":
[
{
"car_model": "Mustang",
"car_brand": "Ford"
},
{
"car_model": "cx-5",
"car_brand": "Mazda"
}
]
}
for cars in data['cars']:
for key, value in cars.items():
if key == "car_model" and value == "cx-5":
cars[key] = "cx-9"
print(data)
If you want to load your json object from a file, let's assume it is called "data.json" and is in the same directory as the python script you are going to run:
import json
with open('data.json') as json_data:
data = json.load(json_data)
for cars in data['cars']:
for key, value in cars.items():
if key == "car_model" and value == "cx-5":
cars[key] = "cx-9"
print(data)
Now if you'd like to write the content to the original file or new file, in this case I am writing to a file called "newdata.json":
import json
import re
with open('data.json') as json_data:
data = json.load(json_data)
print(data)
with open('external.txt') as f:
content = f.read()
print(content)
for cars in data['cars']:
for key, value in cars.items():
if key == "car_model" and value == "cx-5":
cars[key] = content
with open('newdata.json', 'w') as outfile:
json.dump(data, outfile)