I'm trying to append some data into a JSON file inside python.
It should add the CVE-ID into my customer JSON file.
I wasn't able to solve this by myself. If I print my dict after appending it shows the expected result.
But it seems, that the file will not be written after the append. I have also tried to use json.dump() after the "appending-line" - but also without success.
At the moment my code looks like this:
with open("test.json", "r+") as customerdata:
customers_json = json.load(customerdata)
# some other code here...
if cve["cve"]["CVE_data_meta"]["ID"] not in customer["customer"]["already-sent-cve"]:
customers_json["customers"][0]["customer"]["already-sent-cve"].append(cve["cve"]["CVE_data_meta"]["ID"])
My JSON file looks like this:
{
"customers":[
{
"customer":{
"id":"1",
"company-name":"test GmbH",
"alert-email":"xyz#googlemail.com",
"using":[
"xxx",
"xyz"
],
"already-sent-cve":[
"CVE-2013-3738"
# here new CVE
]
}
},
{
"customer":{
"id":"2",
...
}
]
}
FYI: There is another JSON file with the CVE's from which file I'm collecting the data.
Any suggestions how to solve this?
Regards.
EDIT:
Was able to solve this:
with open("test.json", "w") as customerdata:
customers_json["customers"][0]["customer"]["already-sent-cve"].append(cve["cve"]["CVE_data_meta"]["ID"])
json.dump(customers_json, customerdata, indent=2)
You need to write the data back to the file:
with open('test.json', 'w') as customerdata:
json.dump(customers_json, customerdata)
Related
So I have a problem with JSON. The data that I receive from an API looks like this.
{
"weather":[
{
"id":804,
"main":"Clouds",
"description":"overcast clouds",
"icon":"04d"
}
]
}
I can't read the data in the weather cell tough because it's wrapped between those '[ ]'. But if I try to create a JSON file but remove the "[ ]" and try to read it, it works. What can I do? Please help!
If I do the following it works just fine:
import json
data = '''{
"weather":[
{
"id":804,
"main":"Clouds",
"description":"overcast clouds",
"icon":"04d"
}
]
}'''
dict_data = json.loads(data)
print(dict_data.get("weather")[0].get("main"))
>>> "Clouds"
It works as expected. Because it is a list, you have to target the first item, here another dict, which holds the information you want.
I am trying to get a particular value from nested JSON
JSON is as below
{
"ListOn": true,
"currentList": "Counter_Master",
"deployedList": [
{
"name": "Master",
"skipForSchedule": false,
"Type": "regular"
},
{
"plType": "regular",
"skipForSchedule": false,
"name": "Name_test"
}
],
"uptime": 1216.819
}
This is what I did till now
import json
with open('config.json') as f:
#print("file is open")
data = json.load(f)
curr_list = data['deployedPlaylists'] [1] . values()
curr_list = curr_playlist[1]
print("we are finding the name of curr_list[1]", curr_list)
I am not able to pickup 2nd name which is "Name_test" in deployedList[1].name
from shell, I can do with below command, want to do in python, but as I am new to python could not find the exact way.
sudo jq -r '.deployedlists[1].name' _config.json
Requesting for help.
Thanks
I think you just have typos in your code
Just fix data['deployedPlaylists'] [1] . values() to be data['deployedList'] [1]['name'] which will be storing the value Name_test as required.
just take in mind that json.read() returns the value of the json file in python dictionary so to manipulate the values of the json file read more about python dictionaries how they are stored and how to access their values.
I want you to ask for your help.
I need to browse folder with json files and I need to search for one attribute with specific value.
Here is my code:
def listDir():
fileNames = os.listdir(FOLDER_PATH)
for fileName in fileNames:
print(fileName)
with open('C:\\Users\\KamĨo\\Desktop\\UBLjsons\\' + fileName, 'r') as json_file:
data = json.load(json_file)
data_json = json.dumps(data, indent=2, sort_keys=True)
print(data_json)
for line in data_json:
if line['ID'] == 'Kamilko':
print("try") #just to be sure it accessed to this
I am getting this error: TypeError: string indices must be integers
I also tried to search for a solution here but it didnt help me.
Here is my JSON
{
"Invoice": {
"#xmlns": "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
"#xmlns:cac": "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2",
"#xmlns:cbc": "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2",
"ID": "Kamilko",
"IssueDate": "2020-02-09",
"OrderReference": {
"ID": "22"
},
"InvoiceLine": {
"Price": {
"PriceAmount": {
"#currencyID": "EUR",
"#text": "23.50"
},
"BaseQuantity": {
"#unitCode": "C62",
"#text": "1"
}
}
}
}
}
do you have any idea how to do it?
You've loaded your file in using json.load(...). That'll convert the JSON data into a Python dictionary that you can use to access elements:
if data["Invoice"]["OrderReference"]["ID"] == 22:
print("try")
Note that you might want to check the relevant keys exist along the way, in case the structure of your file varies, or you could catch the KeyError that'll come up if the key doesn't exist, using try/except.
Some more background:
When you then call json.dumps(...), you're taking that handy python structure and converting it back into a hard-to-understand string again. I don't think you want or need to do this.
The specific error you have is because dumps has created a string. You're then trying to access an element of that string using the [ ] operator. Strings can only be indexed using integers, e.g. mystr[4], so Python doesn't understand what you're asking it to do with data_json["ID"].
I am writing a program in Python where a JSON local file needs to be updated with the last processed item in a database so that the process kicks off again from that point.
Problem I am having in my code is that sometimes, it adds an extra curly bracket "}" to the end of the code causing the JSON to become invalid. This then breaks the scheduled process until the JSON file is updated.
I know that I can first read the file to the object, then close the file then open it again to write to it but personally it doesn't feel like the code would be as clean given that it is being constantly written to so that the tracking of the last processed item is not lost.
import json
with open(_SETTINGS, 'r+') as settings:
_last_processed = log['#timestamp']
settings_data[env]['last_processed'] = _last_processed
settings.seek(0)
# settings.truncate()
json.dumps(settings_data, settings, indent=2)
The JSON file, _SETTINGS, looks like as follows:
{
"UAT": {
"last_processed": "2019-10-10T00:00:00.0000Z"
},
"DEV": {
"last_processed": "2019-10-10T00:00:00.0000Z"
}
}
Annoyingly what only sometimes gets returned is the above JSON but with an extra closing curly bracket "}" as below.
{
"UAT": {
"last_processed": "2019-10-10T00:00:00.0000Z"
},
"DEV": {
"last_processed": "2019-10-10T00:00:00.0000Z"
}
}}
Anyone can shed some light on this?
I would like to be able to separate some defines meant for configuration, from the script where I would like to use them.
Ex:
## Config ##
antPatHeader = {
# Name
"name": "Antenna_Pattern_Tables",
# Version
"major_version": 0,
"minor_version": 0,
}
Is there a streightforward way, like opening and reading files like
f = open(configFile, "r")
f.read()
f.close()
and then parsing them in the programm.
What is the best way to separate code like one would do for constants from the executing script?
If you want your configuration in a different file and load it as parameters in your script, the easiest way to do it would be to store it a markup language file such as
xml
yaml
json
Your config is already (almost) of a json form, so you can do the following:
config.json:
{
"name": "Antenna_Pattern_Tables",
"major_version": 0,
"minor_version": 0,
}
Then in python:
import json
with open('config.json') as f:
data = json.load(f)
print(data["name"]) #"Antenna_Pattern_Tables"
print(data["major_version"]) #0
If you just want to use python variables from another file you can do:
p2.py:
test = 5
p1.py
import p2
print(p2.test) #5