Handling keys inside a key from .json file - python

I am trying to print an specific key from a JSON file without success.
.json file is:
{
"testing": [
{
"_name": "teste",
"_profile_telphone": "212331233",
"_age": "21"
}
]
}
the function I'm using is:
def load(self):
filename = self.profile_entry.get()
if filename == "":
msg = "Insert a profile name"
messagebox.showinfo("Profile name is empty", msg)
self.profile_entry.focus()
else:
with open('profile_'+filename+'.json', 'r') as outfile:
data = json.load(outfile)
print(data[filename])
outfile.close()
with print(data[filename]) I can print entire
{
"_name": "teste",
"_profile_telphone": "212331233",
"_age": "21"
}
But how can I print only name or age for example?

data is a list of JSONs - you have a json array there, in order to parse it you can do it with a for statement
for element in data[filename]:
print(element[‘_name’])
print(element[‘_profile_telphone’])
print(element[‘_age’])

Related

Modify a sub value of json file using python

I'm trying to create multiple JSON files with different numbers at specific value, this is my code :
import json
json_dict = {
"assetName": "GhostCastle#",
"previewImageNft": {
"mime_Type": "png",
"description": "#",
"fileFromIPFS": "QmNuFreEoJy9CHhXchxaDAwuFXPHu84KYWY9U7S2banxFS/#.png",
"metadataPlaceholder": [
{
"": ""
}
]
}
}
n = 10
for i in range(1, n+1):
json_dict["assetName"] = f"GhostCastle{i}"
json_dict[#What to put here to choose "fileFromIPFS"] = f"QmNuFreEoJy9CHhXchxaDAwuFXPHu84KYWY9U7S2banxFS/{i}.png"
with open(f"{i}.json", 'w') as json_file:
#json.dump() method save dict json to file
json.dump(json_dict, json_file)
so What to put to choose "fileFromIPFS" in the second json_dict

Convert a JSON string to multiple CSV's based on its structure and name it to a certain value

I currently have A JSON file saved containing some data I want to convert to CSV. Here is the data sample below, please note, I have censored the actual value in there for security and privacy reasons.
{
"ID value1": {
"Id": "ID value1",
"TechnischContactpersoon": {
"Naam": "Value",
"Telefoon": "Value",
"Email": "Value"
},
"Disclaimer": [
"Value"
],
"Voorzorgsmaatregelen": [
{
"Attributes": {},
"FileId": "value",
"FileName": "value",
"FilePackageLocation": "value"
},
{
"Attributes": {},
"FileId": "value",
"FileName": "value",
"FilePackageLocation": "value"
},
]
},
"ID value2": {
"Id": "id value2",
"TechnischContactpersoon": {
"Naam": "Value",
"Telefoon": "Value",
"Email": "Value"
},
"Disclaimer": [
"Placeholder"
],
"Voorzorgsmaatregelen": [
{
"Attributes": {},
"FileId": "value",
"FileName": "value",
"FilePackageLocation": "value"
}
]
},
Though I know how to do this (because I already have a function to handle a JSON to CSV convertion) with a simple JSON string without issues. I do not know to this with this kind of JSON file that this kind of a structure layer. Aka a second layer beneath the first. Also you may have noticed that there is an ID value above
Because as may have noticed from structure is actually another layer inside the JSON file. So in total I need to have two kinds of CSV files:
The main CSV file just containing the ID, Disclaimer. This CSV file
is called utility networks and contains all possible ID value's and
the value
A file containing the "Voorzorgsmaatregelen" value's. Because there are multiple values in this section, one CSV file per unique
ID file is needed and needs to be named after the Unique value id.
Deleted this part because it was irrelevant.
Data_folder = "Data"
Unazones_file_name = "UnaZones"
Utilitynetworks_file_name = "utilityNetworks"
folder_path_JSON_BS_JSON = folder_path_creation(Data_folder)
pkml_file_path = os.path.join(folder_path_JSON_BS_JSON,"pmkl.json")
print(pkml_file_path)
json_object = json_open(pkml_file_path)
json_content_unazones = json_object.get("mapRequest").get("UnaZones")
json_content_utility_Networks = json_object.get("utilityNetworks")
Unazones_json_location = json_to_save(json_content_unazones,folder_path_JSON_BS_JSON,Unazones_file_name)
csv_file_location_unazones = os.path.join(folder_path_CSV_file_path(Data_folder),(Unazones_file_name+".csv"))
csv_file_location_Utilitynetwork = os.path.join(folder_path_CSV_file_path(Data_folder),(Unazones_file_name+".csv"))
json_content_utility_Networks = json_object.get("utilityNetworks")
Utility_networks_json_location = json_to_save(json_content_utility_Networks,folder_path_JSON_BS_JSON,Utilitynetworks_file_name)
def json_to_csv_convertion(json_file_path: str, csv_file_location: str):
loaded_json_data = json_open(json_file_path)
# now we will open a file for writing
data_file = open(csv_file_location, 'w', newline='')
# # create the csv writer object
csv_writer = csv.writer(data_file,delimiter = ";")
# Counter variable used for writing
# headers to the CSV file
count = 0
for row in loaded_json_data:
if count == 0:
# Writing headers of CSV file
header = row.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(row.values())
data_file.close()
def folder_path_creation(path: str):
if not os.path.exists(path):
os.makedirs(path)
return path
def json_open(complete_folder_path):
with open(complete_folder_path) as f:
json_to_load = json.load(f) # Modified "objectids" to "object_ids" for readability -sg
return json_to_load
def json_to_save(input_json, folder_path: str, file_name: str):
json_save_location = save_file(input_json, folder_path, file_name, "json")
return json_save_location
So how do I this starting from this?
for obj in json_content_utility_Networks:
Go from there?
Keep in mind that is JSON value has already one layer above every object for every object I need to start one layer below it.
So how do I this?

How to append data to JSON list that doesn't contains any key for that list?

[
{
"name": "name one",
"id": 1
},
{
"name": "name two",
"id": 2
}
]
I want to append object to the list in .json file. how do i do?
You could read the existing json content update it and rewrite the updated list.
import json
with open("myfile.json", "r+") as f:
my_file = f.read() # read the current content
my_list = json.loads(my_file) # convert from json object to dictionary type
dict_obj = {
"name": "name three",
"id": 3
}
my_list.append(dict_obj)
f.seek(0) # sets point at the beginning of the file
f.truncate() # Clear previous content
print(f" going to rewrite {my_list}")
f.write(json.dumps(my_list)) # Write updated version file
I'm not entirely sure of what you are asking but perhaps the code below will help:
const myList = [
{
"name": "name one",
"id": 1
},
{
"name": "name two",
"id": 2
}
]
const myNewItem = {
"name": "name three",
"id": 3
}
const addItemIfDifferentId = (list, newItem) => [...list, !list.map(({id}) =>id).includes(newItem.id) ? {...newItem} : {} ]
const newList = addItemIfDifferentId(myList, myNewItem)
newList
Maybe this will help you:
import json
# When loading a .json files it will be a string:
with open('data.json') as json_file:
x = json.load(json_file) //{"key1":"123", "key2":"456", "key3":"789"}
# python object to be appended
y = {"key4": "101112"}
# Load the json string to be an object type:
z = json.loads(x)
# appending the data
z.update(y)
# the result is a JSON string:
print(json.dumps(z))
with open('data.json', 'w') as outfile:
json.dump(z, outfile)

how to open the json file using python?

ENG_RequestData.json:
{
"appKey": "9c9fa7201e90d3d96718bc3f36ce4cfe1781f2e82f4e5792996623b3b474fee2c77699eb5354f2136063e1ff19c378f0f6dd984471a38ca5c393801bffb062d6",
"appId": "NMDPTRIAL_AutomotiveTesting_NCS61HTTP",
"uId": "Alexander",
"inCodec": "PCM_16_8K",
"outCodec": "PCM_16_8K",
"cmdName": "NVC_TTS_CMD",
"appName": "Python",
"appVersion": "1",
"language": "eng-GB",
"carrier": "carrier",
"deviceModel": "deviceModel",
"cmdDict": {
"tts_voice": "Serena",
"tts_language": "eng-GB",
"locale": "canada",
"application_name": "Testing Python Script",
"organization_id": "NUANCE",
"phone_OS": "4.0",
"phone_network": "wifi",
"audio_source": "SpeakerAndMicrophone",
"location": "47.4925, 19.0513",
"application_session_id": "1234567890",
"utterance_number": "5",
"ui_langugage": "en",
"phone_submodel": "nmPhone2,1",
"application_state_id": "45"
}
}
CODE :
print LNG // it is printing as ENG
ENG_RequestDataFile = scriptPath + "\\" + "ENG_RequestData.json"
print ENG_RequestDataFile // it is printing as C:\Users\\Desktop\OWN\2016_02_11\ENG_RequestData.json
DEU_RequestDataFile = scriptPath + "\\" + "DEU_RequestData.json"
try:
if LNG == 'ENG':
with open(ENG_RequestDataFile) as json_file:
print json_file
JSON_ENGData = json.load(json_file)
print JSON_ENGData
elif LNG == 'DEU':
with open(DEU_RequestDataFile) as json1_file:
JSON_DEUData = json.load(json1_file)
else:
print ("No Other Language")
except:
print ("[ERROR] Cannot open the Request data file")
I am reading a json file from the specific path and the json file is as shown above. there are two json files for one english and german but I am trying to read, but it is printing as [ERROR] Cannot open the Request data file. I am not able to open it. can someone tell me how ?
Try this code:
import json
#Path you posted
path = os.path.join('C:'+os.sep+'Users'+os.sep+'Desktop'
+os.sep+'OWN'+os.sep+'2016_02_11'
+os.sep+'ENG_RequestData.json')
def get_tts(LNG,filename):
try:
if LNG == 'ENG':
with open(filename) as json_file:
JSON_ENGData = json.load(json_file)
print(JSON_ENGData)
elif LNG == 'DEU':
with open(DEU_RequestDataFile) as json_file:
JSON_DEUData = json.load(json_file)
else:
print("No Other Language")
except:
print("[ERROR] Cannot open the Request data file")
#Execute the function
get_tts('ENG',path)
More information here:
https://stackoverflow.com/a/2422864/5915424

Python - write/ADD a new record in file with Json format

I want to add a new record at the end of my file Json, For now it contains
{
"1":
{
"coef":987,
"Term":
{
"x1":6,"x2":0,"x3":8
}
}
}
im reading this file like this :
try:
json_data=open ("/home/sage/content.txt")
data=json.load (json_data)
except IOError:
print "Can't open your file"
how to add a new record at the end of file.
After reading the data , you can't add to the file, you need to create a new file (with the same name if you want):
data['added_data'] = 'some data added'
write_file = open("/home/sage/content.txt", "w")
write_file.write(json.dumps(data))
If you are using python 2.5 or newer you should use with statement dealing with files:
import json
with open('content.txt', 'r') as f:
data = json.load(f)
data["2"] = {
"coef":987,
"Term":
{
"x1":6,"x2":0,"x3":8
}
}
with open('content.txt', 'w') as f:
json.dump(data, f)

Categories