How do i rename json key using python? - python

I have json file, i need to rename folder_path key to backup_folder_path using python:
{
"urn:adsk.wipprod:dm.lineage:smth": {
"bim_manifest_urn": "urn:foo/bar/z",
"gs_id": "foobar",
"versions": {
"1": "1"
},
"folder_path": "/foo/bar"
},
"urn:adsk.wipprod:dm.lineage:smth": {
"bim_manifest_urn": "urn:foo/bar",
"gs_id": "foobar1",
"versions": {
"1": "1"
},
"folder_path": "/foo/barŠ”"
},
What I tried to do:
def edit_string_name():
with open(r"smth.json", encoding="utf-8") as json_data:
data = json.load(json_data)
data = {'folder_path'}
data['backup_folder_path'] = data.pop('folder_path')
print(data)
if __name__ == '__main__':
edit_string_name()
But nothing seems to happen.
When I tried to cycle through I got nonsense in terminal.

This should do the job
def edit_string_name():
with open("smth.json", "r+", encoding="utf-8") as file:
data = json.load(file)
content = data["urn:adsk.wipprod:dm.lineage:smth"]
content["backup_folder_path"] = content["folder_path"]
content.pop("folder_path")
data["urn:adsk.wipprod:dm.lineage:smth"] = content
# Updating the file
file.seek(0)
file.write(json.dumps(data, indent=4))
file.truncate()
edit_string_name()

Related

How to write a variable in a json file?

I searched for a long time but I am not really familiar with python and json and I can't find the answer of my problem.
Here is my Python script
import json
jsonFile = open("config.json", "r")
data = json.load(jsonFile)
data.format(friendly, teaching, leader, target)
print(data)
Here is json the file:
{
"commend": {
"friendly": {},
"teaching": {},
"leader": {}
},
"account": {
"username": "",
"password": "",
"sharedSecret": ""
},
"proxy": {
"enabled": false,
"file": "proxies.txt",
"switchProxyEveryXaccounts": 5
},
"type": "COMMEND",
"method": "SERVER",
"target": "https://steamcommunity.com/id/{}",
"perChunk": 20,
"betweenChunks": 300000,
"cooldown": 28800000,
"steamWebAPIKey": "{}",
"disableUpdateCheck": false
}
I tried .format but we can't use this method with with a dictionary.
With your help I managed to find the answer A big thank you for your speed and your help ! Here is what I did:
import json
jsonFile = open("config.json", "r")
data = json.load(jsonFile)
(data['commend']['friendly']) = nbfriendly
(data['commend']['teaching']) = nbteaching
(data['commend']['leader']) = nbleader
print(data)
print(data)
A json file is a dictionary, so you can use dict methods with it. Here is the code:
import json
with open("config.json", "r") as json_file:
data = json.load(json_file)
# Let's say you want to add the string "Hello, World!" to the "password" key
data["account"]["password"] += "Hello, World!"
# Or you can use this way to overwrite anything already written inside the key
data["account"]["password"] = "Hello, World!"
print(data)
You can add data by tranversing through it like a dictionary:
data['key'] = value
Example:
dic["commend"]["friendly"]={'a':1}

How do I maintain the same structure when reading from, modifying and writing back to a JSON file?

I am currently reading in a JSON file, adding a key and writing it back out to the same file using this procedure
with open('data.json', 'r+') as f:
data = json.load(f)
temp_key={"test":"val"}
data["test"]["new_key"] = temp_key
f.seek(0) # <--- should reset file position to the beginning.
json.dump(data, f, indent=2)
f.truncate() # remove remaining part
(adopted from here)
but the issue is that it does not maintain order. for instance if I read in:
{
"test": {
"something": "something_else"
},
"abc": {
"what": "huh"
}
}
the output turns out as:
{
"abc": {
"what": "huh"
},
"test": {
"something": "something_else",
"new_key": {
"test": "val"
}
}
}
When I would like it to be:
{
"test": {
"something": "something_else",
"new_key": {
"test": "val"
}
},
"abc": {
"what": "huh"
}
}
I realise that JSON is a key/value based structure and the order does not matter, but is there a way of making the modification and maintaining the original structure?
As I said in a comment, you can use a collections.OrderedDict along with the optional object_pairs_hook keyword argument accepted by json.load() (in Python 2.7) to preserve the order of the original data when you rewrite the file.
This is what I meant:
#!/usr/bin/env python2
from collections import OrderedDict
import json
with open('ordered_data.json', 'r+') as f:
data = json.load(f, object_pairs_hook=OrderedDict)
temp_key = {"test": "val"}
data["test"]["new_key"] = temp_key
f.seek(0) # Reset file position to the beginning.
json.dump(data, f, indent=2)
f.truncate() # Remove remaining part.

how to load json file using python (not manually)?

code :
userid1='u123'
userid2='u124'
ids= (userid1,userid2)
fake = Faker('en_US')
for ind in ids:
for idx in range(1):
sms = {
"id": ind ,
"name": fake.name(),
"email": fake.email(),
"gender": "MALE",
}
f_name = '{}.json'.format(ind)
with open(f_name, 'w') as fp:
#Save the dictionary
json.dump(sms, fp, indent=4)
print(sms)
file1 = filename.json ( how to get the *ind* value here i.e., userid)
fd1=open("filename.json")
json_content1 = fd1.read()
fd1.close()
how to open file that has been saved f_name = '{}.json'.format(ind) here . without mentioning the file name manually. file names are saved using ind. so how to use ind here and open the file
this code can help you to get data from json file: you can get any filed from the json data by typing data["name-of-filed"]:
import json
userid1='json_file1'
ids= [userid1]
for ind in ids:
f_name = '{}.json'.format(ind)
with open(f_name, 'r') as outfile:
data = json.loads(outfile.read())
print(data["name"])
print(data)
here is an exemple :
file.json :
{
"name": "Ghassen",
"apiVersion": "v1"
}
output :
Ghassen
{'name': 'Ghassen', 'apiVersion': 'v1'}

Search JSON file from python

I am trying to search for a variable in a JSON file.
Current JSON file (devices.json) is:
{
"NYC": {
"Floor1": [
{
"name": "server1",
"ip": "1.1.1.1"
},
{
"name": "server2",
"ip": "1.1.1.2"
}
],
"Floor2": [
...
],
"sitenum": 1
},
"Boston": {
...
"sitenum": 2
}
...
}
Two questions:
I am new to JSON, so is this formatted correctly for
lists/dictionaries?
I'd like to preform a python query to display Floor(s){name, ip} for sitenum (x)
Current Python file is
import json
with open('devices.json') as jsonfile:
data = json.load(jsonfile)
Thanks!
this python script will return the floor details as a list of json values for a given sitenum and floor.
import json
def get_floor_details(sitenum, floor, data):
for k,v in data.items():
if v['sitenum'] == sitenum:
return(v[floor])
with open('sample.json') as json_file:
data = json.load(json_file)
sitenum = 1
floor = 'Floor1'
floor_details = get_floor_details(sitenum, floor, data)
print(floor_details)
Output:
[{'name': 'server1', 'ip': '1.1.1.1'}, {'name': 'server2', 'ip': '1.1.1.2'}]
def findFloor(site_num_val, data):
return_val = {}
for each_loc in data:
if site_num_val == each_loc["sitenum"]:
return_val = data[each_loc].copy()
del return_val["sitenum"]
break
else:
print "sitenum not found"
return return_val
I hope this solves your problem in trying to get the information.

Writing dicitonary to JSON using Python

I'm new to Python programming, so do bear with me if I make any mistakes anywhere
I'm trying to write a json file using 2 dictionaries and dump the output to the file using the following code on Windows
import json
import sys
import string
from time import strftime
scan_results = open("scan_results.txt", "r")
saved = sys.stdout
f = file('report.json', 'wb')
sys.stdout = f
for line in scan_results:
if ".jpg" in line:
lst = []
result = line.split('\\')
result_split = result[5].split(' ')
filename = result_split[0]
raw_status = result_split[3]
if "OK" in raw_status:
status = "Okay"
status_code = "0"
dict = {'FileName': filename, 'DateTime': strftime("%Y-%m-%d %H:%M:%S"), 'statusCode': status_code, 'Description': status}
dict2 = {filename : dict}
print json.dumps(dict2)
sys.stdout = saved
f.close()
print "JSON report written"
The problem is, the output that I have is
{
"car-30537.jpg": {
"statusCode": "0",
"DateTime": "2012-02-07 09:52:26",
"Description": "Okay",
"FileName": "car-30537.jpg"
}
}{
"car-30538.jpg": {
"statusCode": "0",
"DateTime": "2012-02-07 09:52:26",
"Description": "Okay",
"FileName": "car-30538.jpg"
}
}
whereas the output that I want is
{
"car-30537.jpg": {
"statusCode": "0",
"DateTime": "2012-02-07 09:52:26",
"Description": "Okay",
"FileName": "car-30537.jpg"
},
{
"car-30538.jpg": {
"statusCode": "0",
"DateTime": "2012-02-07 09:52:26",
"Description": "Okay",
"FileName": "car-30538.jpg"
}
}
Is there any ways to correct this problem? Thanks in advance
You are making lots of dicts, while you only need one main containing one:
import json
import sys
import string
from time import strftime
scan_results = open("scan_results.txt", "r")
saved = sys.stdout
f = file('report.json', 'wb')
sys.stdout = f
dict2 = {} #Create one output dict
for line in scan_results:
if ".jpg" in line:
lst = []
result = line.split('\\')
result_split = result[5].split(' ')
filename = result_split[0]
raw_status = result_split[3]
if "OK" in raw_status:
status = "Okay"
status_code = "0"
dict2[filename] = {'FileName': filename, 'DateTime': strftime("%Y-%m-%d %H:%M:%S"), 'statusCode': status_code, 'Description': status} #Add to that dict.
print json.dumps(dict2) #Print it out at the end.
sys.stdout = saved
f.close()
print "JSON report written"
I added comments to modified lines.

Categories

Resources