Who will help me with the code?
I have a json file that looks like this:
{"entries": [{"attributes": {"cn": ["John Doe"], "lastLogon": ["133137573913265630"], "sn": ["Doe"], "userAccountControl": ["4096"]},"dn": "CN=John Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local"}, {"attributes": {"cn": ["Jane Doe"], "lastLogon": [], "sn": ["Doe"], "userAccountControl": ["514"]}, "dn": "CN=Jane Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local"}]}
which I create with the json module
for dc in dcList:
LDAP_HOST = dc['hostName']
def ldap_server():
return Server(LDAP_HOST, use_ssl=True, tls=tls_configuration, get_info=ALL_ATTRIBUTES)
conn = ldap_connection()
conn.search(LDAP_BASE_DN, LDAP_OBJECT_FILTER, attributes=user_attr_list)
### write data from addc to JSON file
jsonFile = rootPath dataPath LDAP_HOST "-" jsonUsersData
data = json.loads(conn.response_to_json())
with open(jsonFile, 'w') as f:
json.dump(data, f)
I would like the file to look more readable, for example:
{
"entries":
[
{
"attributes": {
"cn": ["John Doe"],
"lastLogon": ["133137573913265630"],
"sn": ["Doe"],
"userAccountControl": ["4096"]
},
"dn": "CN=John Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local"
},
{
"attributes": {
"cn": ["Jane Doe"],
"lastLogon": [],
"sn": ["Doe"],
"userAccountControl": ["514"]
},
"dn": "CN=Jane Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local"
}
]
}
and ideally, the file should be converted to the following format:
"users":
[
{
"cn": ["John Doe"],
"lastLogon": ["133137573913265630"],
"sn": ["Doe"],
"userAccountControl": ["4096"]
"dn": "CN=John Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local"
},
{
"cn": ["Jane Doe"],
"lastLogon": [],
"sn": ["Doe"],
"userAccountControl": ["514"]
"dn": "CN=Jane Doe,OU=Users,OU=UNIVERSUM,DC=universum,DC=local"
}
]
}
CodePudding user response:
You can use json.dump
arguments like json.dump(data, indent=2)
.
The second ("ideal") format is not a valid JSON, so it's (AFAIK) achievable only using some other string processing methods (if it's a typo, the JSON format might be valid, however it's not possible to change format using json.dump
arguments and it will require few lines of Python code in order to change the json structure).
EDIT: Also there is more possible using json.dump
options, some sorting etc. See docs here.
CodePudding user response:
You can achieve this using below line of code
json.dump(data, f,indent=4,sort_keys=True)
CodePudding user response:
you already have a few answers but here is the full python code
import json
json_string='SOME_JSON_HERE'
try:
parsed_json=json.loads(json_string)
out=(json.dumps(parsed_json, indent=4,sort_keys=False))
print(out)
except Exception as e:
print(repr(e))