Can't Go Past First Dict In JSON File - python

I'm trying to iterate through a JSON file to search for specific parts and print out that portion of the file. But my code only works for the first dict in the file, anything past that will have my code print out that the part of the JSON file doesn't exit. Here is the JSON file:
[
{
"Name": "Debian",
"Version": "9",
"Install": "apt",
"Owner": "SPI",
"Kernel": "4.9"
},
{
"Name": "Ubuntu",
"Version": "17.10",
"Install": "apt",
"Owner": "Canonical",
"Kernel": "4.13"
},
{
"Name": "Fedora",
"Version": "26",
"Install": "dnf",
"Owner": "Red Hat",
"Kernel": "4.13"
},
{
"Name": "CentOS",
"Version": "7",
"Install": "yum",
"Owner": "Red Hat",
"Kernel": "3.10"
},
{
"Name": "OpenSUSE",
"Version": "42.3",
"Install": "zypper",
"Owner": "Novell",
"Kernel": "4.4"
},
{
"Name": "Arch Linux",
"Version": "Rolling Release",
"Install": "pacman",
"Owner": "SPI",
"Kernel": "4.13"
},
{
"Name": "Gentoo",
"Version": "Rolling Release",
"Install": "emerge",
"Owner": "Gentoo Foundation",
"Kernel": "4.12"
}
]
Here is my Code:
import json
jsonfile = raw_input("Choose a json file: ")
type(jsonfile)
name = input("Type in the name: ")
type(name)
with open (jsonfile) as myfile:
data = myfile.read()
obj = json.loads(data)
for i in obj:
if i["Name"] == name:
print(i["Version"])
break
else:
print("Title not found")
break
So say I enter the name "Debian" I get the version number just fine. But if I type in "Fedora" for example, I get the "Title not found" portion of my code. Which means that the name wasn't in the JSON file but it is. Any help would be appreciated.

For the sake of simplicity:
s = [
{
"Name": "Debian",
"Version": "9",
"Install": "apt",
"Owner": "SPI",
"Kernel": "4.9"
},
{
"Name": "Ubuntu",
"Version": "17.10",
"Install": "apt",
"Owner": "Canonical",
"Kernel": "4.13"
},
{
"Name": "Fedora",
"Version": "26",
"Install": "dnf",
"Owner": "Red Hat",
"Kernel": "4.13"
},
{
"Name": "CentOS",
"Version": "7",
"Install": "yum",
"Owner": "Red Hat",
"Kernel": "3.10"
},
{
"Name": "OpenSUSE",
"Version": "42.3",
"Install": "zypper",
"Owner": "Novell",
"Kernel": "4.4"
},
{
"Name": "Arch Linux",
"Version": "Rolling Release",
"Install": "pacman",
"Owner": "SPI",
"Kernel": "4.13"
},
{
"Name": "Gentoo",
"Version": "Rolling Release",
"Install": "emerge",
"Owner": "Gentoo Foundation",
"Kernel": "4.12"
}
]
Using list-comprehension:
search = 'Fedora'
print([x['Version'] for x in s if x['Name'] == search])
OUTPUT:
['26']
Explanation:
search = 'Fedora'
for elem in s: # for each elem in the list
if elem['Name'] == search: # check if the Name is what you're looking for
print(elem['Version']) # print the Version if it is
OUTPUT:
26

Your loop always ends on the first iteration.
Corrected version:
# ...
for i in obj:
if i["Name"] == name:
print(i["Version"])
break
else:
print("Title not found")
http://book.pythontips.com/en/latest/for_-_else.html

With break you're exiting immediately the for loop as soon as one element doesn't match name, hence the code works only for the first match.
This is how one could write a loop with a break statement
found = False
for i in obj:
if i["Name"] == name:
found = True
break
if found:
print(i["Version"])
else:
print("Title not found")
If the loop is inside a function you could simply use return in place of break
def search(obj, name):
for i in obj:
if i["Name"] == name:
return i["Version"]
return "Title not found"
But the pythonic way to implement this would be:
next((i["Version"] for i in iter(obj) if i["Name"] == name), "Title not found")
next will stop after the first match as well.
Example:
obj= [
{
"Name": "Debian",
"Version": "9"
},
{
"Name": "Ubuntu",
"Version": "17.10"
},
{
"Name": "Fedora",
"Version": "26"
}]
name = "Fedora"
next((i["Version"] for i in iter(obj) if i["Name"] == name), "Title not found")
# Out:
# '26'

Related

Remove key but keep value in JSON [Python]

I need to "Semi-Flatten" a JSON object where i have a JSON object with nested items. I have tried to use the flat_json with pandas and other "flatten_json" and json_normalize code in stackoverflow but i end up with completely flatten JSON (something i do not need).
Here is the JSON structure:
[{
"Stat": {
"event": "03458188-abf9-431c-8144-ad49c1d069ed",
"id": "102e1bb1f28ca44b70d02d33380b13",
"number": "1121",
"source": "",
"datetime": "2023-01-13T00:00:00Z",
"status": "ok"
},
"Goal": {
"name": "goalname"
},
"Fordel": {
"company": "companyname"
},
"Land": {
"name": "landname"
}
}, {
"Stat": {
"event": "22222",
"id": "44444",
"number": "5555",
"source": "",
"datetime": "2023-01-13T00:00:00Z",
"status": "ok"
},
"Goal": {
"name": "goalname2"
},
"Fordel": {
"company": "companyname2"
},
"Land": {
"name_land": "landname2"
}
}]
The result i need is this:
[{
"event": "03458188-abf9-431c-8144-ad49c1d069ed",
"id": "102e1bb1f28ca44b70d02d33380b13",
"number": "1121",
"source": "",
"datetime": "2023-01-13T00:00:00Z",
"status": "ok",
"name": "goalname",
"company": "companyname",
"name_land": "landname"
}, {
"event": "22222",
"id": "44444",
"number": "5555",
"source": "",
"datetime": "2023-01-13T00:00:00Z",
"status": "ok",
"name": "goalname2",
"company": "companyname2",
"name_land": "landname2"
}]
If this can be used with pandas or other json packages it would be great.
Coded i have tried: (copy/paste from another question/answer)
def flatten_data(y):
out = {}
def flatten(x, name=''):
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '_')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '_')
i += 1
else:
out[name[:-1]] = x
flatten(y)
return out
That gives me:
{
"0_event": "03458188-abf9-431c-8144-ad49c1d069ed",
"0_id": "102e1bb1f28ca44b70d02d33380b13",
......
"1_event": "102e1bb1f28ca44b70d02d33380b13",
"1_id": "102e1bb1f28ca44b70d02d33380b13",
etc...
}
Map the flatten_data function over the list instead of flattening the entire list.
result = list(map(flatten_data, source)))

Create JSON having a specific structure in Python by merging dictionaries in a blank master dictionary

So, I have JSON data that I am getting from an HTML form. I have to format this data to have a specific JSON structure as shown below.
[
{
"Header": "Stats",
"Line_01": "Line 01",
"Line_02": "Line 02",
"Line_03": "Line 03",
"Line_04": "Line 04",
"Line_05": "Line 05",
"Line_06": "Line 06",
"Line_07": "Line 07"
},
{
"Header": "JUV",
"Line_01": "89",
"Line_02": "34",
"Line_03": "765",
"Line_04": "123",
"Line_05": "1",
"Line_06": "4",
"Line_07": "455"
},
{
"Header": "SMP",
"Line_01": "12",
"Line_02": "89",
"Line_03": "124",
"Line_04": "678",
"Line_05": "92",
"Line_06": "120",
"Line_07": "5"
}
]
JSON I have from the HTML form is:
[
{
"name": "00",
"value": "JUV"
},
{
"name": "00",
"value": "STATS"
},
{
"name": "00",
"value": "SMP"
},
{
"name": "00",
"value": "89"
},
{
"name": "01",
"value": "LINE 01"
},
{
"name": "02",
"value": "12"
},
{
"name": "03",
"value": "34"
},
{
"name": "04",
"value": "LINE 02"
},
{
"name": "05",
"value": "89"
},
{
"name": "06",
"value": "765"
},
{
"name": "07",
"value": "LINE 03"
},
{
"name": "08",
"value": "124"
},
{
"name": "09",
"value": "123"
},
{
"name": "10",
"value": "LINE 04"
},
{
"name": "11",
"value": "678"
},
{
"name": "12",
"value": "1"
},
{
"name": "13",
"value": "LINE 05"
},
{
"name": "14",
"value": "92"
},
{
"name": "15",
"value": "4"
},
{
"name": "16",
"value": "LINE 06"
},
{
"name": "17",
"value": "120"
},
{
"name": "18",
"value": "455"
},
{
"name": "19",
"value": "LINE 07"
},
{
"name": "20",
"value": "5"
}
]
The form looks like this: HTML form - Image on Pasteboard
The Python code I am trying so far is:
import json
jarr = []
final_file = {}
json_template = {
"Header": "",
"Line_01": "",
"Line_02": "",
"Line_03": "",
"Line_04": "",
"Line_05": "",
"Line_06": "",
"Line_07": ""
}
with open("testo101.json",) as f:
jdata = json.load(f)
k = 0
for i in range(8):
a =[]
for j in range(3):
a.append(jdata[k]['value'])
k+=1
jarr.append(a)
for i, x in enumerate(json_template):
json_template[x]=jarr[i][1]
final_file.update(json_template)
for i, x in enumerate(json_template):
json_template[x]=jarr[i][0]
final_file.update(json_template)
for i, x in enumerate(json_template):
json_template[x]=jarr[i][2]
final_file.update(json_template)
print(final_file)
So what I have done so far is:
Import the JSON file I got from HTML form.
Covert it into a 3x8 matrix... so I can get values of each column
easily.
I can fill values from the JSON in the json_template dictionary with
the help of 2D array I just created.
The Problem:
I can't figure out how to merge the 3 dictionaries that I am generating from each column of the 2D array into a single dictionary final_file so I can dump it as a JSON file and that's what I want. How can I do this... or if there is some other better way to do this then please help.
Thanks.
These code should do the job:
import json
jarr = []
final_file = [] # CHANGE #1
json_template = {
"Header": "",
"Line_01": "",
"Line_02": "",
"Line_03": "",
"Line_04": "",
"Line_05": "",
"Line_06": "",
"Line_07": ""
}
with open("testo101.json",) as f:
jdata = json.load(f)
k = 0
for i in range(8):
a =[]
for j in range(3):
a.append(jdata[k]['value'])
k+=1
jarr.append(a)
for i, x in enumerate(json_template):
json_template[x]=jarr[i][1]
final_file.append(json_template.copy()) # CHANGE #2
for i, x in enumerate(json_template):
json_template[x]=jarr[i][0]
final_file.append(json_template.copy()) # CHANGE #2
for i, x in enumerate(json_template):
json_template[x]=jarr[i][2]
final_file.append(json_template.copy()) # CHANGE #2
with open('yourjson.json', 'w') as jsonfile:
json.dump(final_file, jsonfile, indent=4)
I made two changes to your code:
You need a list of dictionaries, not just one dictionary to dump three dictionaries, so I changed final_file to a list.
After you make each json_template, I attached a copy of the template to the list. (.copy() is important, otherwise later changes will be reflected in the previous entries and you end up getting three of the same item).
I wrote the dumping code and attached it to the end. You can open yourjson.json to see the result.

A way to find if multiple keys exist under the same name?

Ok so im making this discord bot that uses the Google Calendar API to get my events, when I call the command in discord it will give me a list of my events for the week. It works fine for getting only one event, but since each event has the same key names in the json im finding it hard to find if multiple keys exist within the json file, exp.
[
{
"created": "2020-05-05T18:30:24.000Z",
"creator": {
"email": "email goes here",
"self": true
},
"end": {
"dateTime": "2020-05-05T15:00:00-04:00"
},
"etag": "\"3177446035674000\"",
"htmlLink": "https://www.google.com/calendar/event?eid=MWZqdXRqZW9panZ0YmZycDVnZ2R1OG1kbnAgcHJvamVjdG5vdGlmeWNhbEBt",
"iCalUID": "1fjutjeoijvtbfrp5ggdu8mdnp#google.com",
"id": "1fjutjeoijvtbfrp5ggdu8mdnp",
"kind": "calendar#event",
"organizer": {
"email": "email goes here",
"self": true
},
"reminders": {
"useDefault": true
},
"sequence": 0,
"start": {
"dateTime": "2020-05-05T14:00:00-04:00"
},
"status": "confirmed",
"summary": "Event title 1",
"updated": "2020-05-05T23:56:57.837Z"
},
{
"created": "2020-05-06T17:48:42.000Z",
"creator": {
"email": "email goes here",
"self": true
},
"end": {
"dateTime": "2020-05-06T15:00:00-04:00"
},
"etag": "\"3177575538452000\"",
"htmlLink": "https://www.google.com/calendar/event?eid=MmtzdDVyb29mZzhydGhyb25ja2UxazVkbmcgcHJvamVjdG5vdGlmeWNhbEBt",
"iCalUID": "2kst5roofg8rthroncke1k5dng#google.com",
"id": "2kst5roofg8rthroncke1k5dng",
"kind": "calendar#event",
"organizer": {
"email": "email goes here",
"self": true
},
"reminders": {
"useDefault": true
},
"sequence": 1,
"start": {
"dateTime": "2020-05-06T14:00:00-04:00"
},
"status": "confirmed",
"summary": "Event title 2",
"updated": "2020-05-06T17:56:09.226Z"
}
So as you can see there are 2 keys for each event, the key I want to use is the "summary" key to get the event name.
In my code, its fine for getting the first key, but in the nature of the program, there may be lots of events for a given week, so how can I test if there are multiple keys, then if there are, print the others, if there arent, print saying there arent any more events. This is what I have so far:
#use google calendar api token
import pickle
credentials = pickle.load(open('token.pickle', 'rb'))
service = build('calendar', 'v3', credentials=credentials)
#get id (aka calendar name)
calendar_list = service.calendarList().list().execute()
calendar_id = calendar_list['items'][0]['id']
#get items from id
calendar_list = service.events().list(calendarId=calendar_id).execute()
#print(calendar_list['items'])
#making json
loadjson = json.dumps(calendar_list['items'])
info = json.loads(loadjson)
with open("formatteddata.json", "w") as formatted_data:
json.dump(info, formatted_data, indent=4, sort_keys=True)
#print title of event (item name)
itemtitle = info[0]["summary"]
print (itemtitle)
if ["summary"][1] in loadjson:
print("2 exist")
else:
print('does not exist')
The end portion is what Im having trouble with. I get a list index out of range error, not sure if I have the right idea or if im super far off
Hope this is what you need:
inputData = [
{
"created": "2020-05-05T18:30:24.000Z",
"creator": {
"email": "email goes here",
"self": "true"
},
"end": {
"dateTime": "2020-05-05T15:00:00-04:00"
},
"etag": "\"3177446035674000\"",
"htmlLink": "https://www.google.com/calendar/event?eid=MWZqdXRqZW9panZ0YmZycDVnZ2R1OG1kbnAgcHJvamVjdG5vdGlmeWNhbEBt",
"iCalUID": "1fjutjeoijvtbfrp5ggdu8mdnp#google.com",
"id": "1fjutjeoijvtbfrp5ggdu8mdnp",
"kind": "calendar#event",
"organizer": {
"email": "email goes here",
"self": "true"
},
"reminders": {
"useDefault": "true"
},
"sequence": 0,
"start": {
"dateTime": "2020-05-05T14:00:00-04:00"
},
"status": "confirmed",
"summary": "Event title 1",
"updated": "2020-05-05T23:56:57.837Z"
},
{
"created": "2020-05-06T17:48:42.000Z",
"creator": {
"email": "email goes here",
"self": "true"
},
"end": {
"dateTime": "2020-05-06T15:00:00-04:00"
},
"etag": "\"3177575538452000\"",
"htmlLink": "https://www.google.com/calendar/event?eid=MmtzdDVyb29mZzhydGhyb25ja2UxazVkbmcgcHJvamVjdG5vdGlmeWNhbEBt",
"iCalUID": "2kst5roofg8rthroncke1k5dng#google.com",
"id": "2kst5roofg8rthroncke1k5dng",
"kind": "calendar#event",
"organizer": {
"email": "email goes here",
"self": "true"
},
"reminders": {
"useDefault": "true"
},
"sequence": 1,
"start": {
"dateTime": "2020-05-06T14:00:00-04:00"
},
"status": "confirmed",
"summary": "Event title 2",
"updated": "2020-05-06T17:56:09.226Z"
}
]
#print title of event (item name)
itemtitle = inputData[0]["summary"]
print (itemtitle)
counter = 0
for event in inputData:
if "summary" in event:
counter = counter + 1
if counter > 0:
outputMsg = str(counter) + " exist"
else:
outputMsg = "does not exist"
print(outputMsg)

Adding a key/value pair once I have recursively searched a dict

I have searched a nested dict for certain keys, I have succeeded in being able to locate the keys I am looking for, but I am not sure how I can now add a key/value pair to the location the key I am looking for is. Is there a way to tell python to append the data entry to the location it is currently looking at?
Code:
import os
import json
import shutil
import re
import fileinput
from collections import OrderedDict
#Finds and lists the folders that have been provided
d='.'
folders = list(filter (lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d)))
print("Folders found: ")
print(folders)
print("\n")
def processModelFolder(inFolder):
#Creating the file names
fileName = os.path.join(d, inFolder, inFolder + ".mdl")
fileNameTwo = os.path.join(d, inFolder, inFolder + ".vg2.json")
fileNameThree = os.path.join(d, inFolder, inFolder + "APPENDED.vg2.json")
#copying the json file so the new copy can be appended
shutil.copyfile(fileNameTwo, fileNameThree)
#assigning IDs and properties to search for in the mdl file
IDs = ["7f034e5c-24df-4145-bab8-601f49b43b50"]
Properties = ["IDSU_FX[0]"]
#Basic check to see if IDs and Properties are valid
for i in IDs:
if len(i) != 36:
print("ID may not have been valid and might not return the results you expect, check to ensure the characters are correct: ")
print(i)
print("\n")
if len(IDs) == 0:
print("No IDs were given!")
elif len(Properties) == 0:
print("No Properties were given!")
#Reads code untill an ID is found
else:
with open(fileName , "r") as in_file:
IDCO = None
for n, line in enumerate(in_file, 1):
if line.startswith('IDCO_IDENTIFICATION'):
#Checks if the second part of each line is a ID tag in IDs
if line.split('"')[1] in IDs:
#If ID found it is stored as IDCO
IDCO = line.split('"')[1]
else:
if IDCO:
pass
IDCO = None
#Checks if the first part of each line is a Prop in Propterties
elif IDCO and line.split(' ')[0] in Properties:
print('Found! ID:{} Prop:{} Value: {}'.format(IDCO, line.split('=')[0][:-1], line.split('=')[1][:-1]))
print("\n")
#Stores the property name and value
name = str(line.split(' ')[0])
value = str(line.split(' ')[2])
#creates the entry to be appended to the dict
#json file editing
with open(fileNameThree , "r+") as json_data:
python_obj = json.load(json_data)
#calling recursive search
get_recursively(python_obj, IDCO, name, value)
with open(fileNameThree , "w") as json_data:
json.dump(python_obj, json_data, indent = 1)
print('Processed {} lines in file: {}'.format(n , fileName))
def get_recursively(search_dict, IDCO, name, value):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided, when key "id" is found it checks to,
see if its value is the current IDCO tag, if so it appends the new data.
"""
fields_found = []
for key, value in search_dict.iteritems():
if key == "id":
if value == IDCO:
print("FOUND IDCO IN JSON: " + value +"\n")
elif isinstance(value, dict):
results = get_recursively(value, IDCO, name, value)
for result in results:
x = 1
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = get_recursively(item, IDCO, name, value)
for another_result in more_results:
x=1
return fields_found
for modelFolder in folders:
processModelFolder(modelFolder)
In short, once it finds a key/id value pair that I want, can I tell it to append name/value to that location directly and then continue?
nested dict:
{
"id": "79cb20b0-02be-42c7-9b45-96407c888dc2",
"tenantId": "00000000-0000-0000-0000-000000000000",
"name": "2-stufiges Stirnradgetriebe",
"description": null,
"visibility": "None",
"method": "IDM_CALCULATE_GEAR_COUPLED",
"created": "2018-10-16T10:25:20.874Z",
"createdBy": "00000000-0000-0000-0000-000000000000",
"lastModified": "2018-10-16T10:25:28.226Z",
"lastModifiedBy": "00000000-0000-0000-0000-000000000000",
"client": "STRING_BEARINX_ONLINE",
"project": {
"id": "10c37dcc-0e4e-4c4d-a6d6-12cf65cceaf9",
"name": "proj 2",
"isBookmarked": false
},
"rootObject": {
"id": "6ff0010c-00fe-485b-b695-4ddd6aca4dcd",
"type": "IDO_GEAR",
"children": [
{
"id": "1dd94d1a-e52d-40b3-a82b-6db02a8fbbab",
"type": "IDO_SYSTEM_LOADCASE",
"children": [],
"childList": "SYSTEMLOADCASE",
"properties": [
{
"name": "IDCO_IDENTIFICATION",
"value": "1dd94d1a-e52d-40b3-a82b-6db02a8fbbab"
},
{
"name": "IDCO_DESIGNATION",
"value": "Lastfall 1"
},
{
"name": "IDSLC_TIME_PORTION",
"value": 100
},
{
"name": "IDSLC_DISTANCE_PORTION",
"value": 100
},
{
"name": "IDSLC_OPERATING_TIME_IN_HOURS",
"value": 1
},
{
"name": "IDSLC_OPERATING_TIME_IN_SECONDS",
"value": 3600
},
{
"name": "IDSLC_OPERATING_REVOLUTIONS",
"value": 1
},
{
"name": "IDSLC_OPERATING_DISTANCE",
"value": 1
},
{
"name": "IDSLC_ACCELERATION",
"value": 9.81
},
{
"name": "IDSLC_EPSILON_X",
"value": 0
},
{
"name": "IDSLC_EPSILON_Y",
"value": 0
},
{
"name": "IDSLC_EPSILON_Z",
"value": 0
},
{
"name": "IDSLC_CALCULATION_WITH_OWN_WEIGHT",
"value": "CO_CALCULATION_WITHOUT_OWN_WEIGHT"
},
{
"name": "IDSLC_CALCULATION_WITH_TEMPERATURE",
"value": "CO_CALCULATION_WITH_TEMPERATURE"
},
{
"name": "IDSLC_FLAG_FOR_LOADCASE_CALCULATION",
"value": "LB_CALCULATE_LOADCASE"
},
{
"name": "IDSLC_STATUS_OF_LOADCASE_CALCULATION",
"value": false
}
],
"position": 1,
"order": 1,
"support_vector": {
"x": 0,
"y": 0,
"z": 0
},
"u_axis_vector": {
"x": 1,
"y": 0,
"z": 0
},
"w_axis_vector": {
"x": 0,
"y": 0,
"z": 1
},
"role": "_none_"
},
{
"id": "ab7fbf37-17bb-4e60-a543-634571a0fd73",
"type": "IDO_SHAFT_SYSTEM",
"children": [
{
"id": "7f034e5c-24df-4145-bab8-601f49b43b50",
"type": "IDO_RADIAL_ROLLER_BEARING",
"children": [
{
"id": "0b3e695b-6028-43af-874d-4826ab60dd3f",
"type": "IDO_RADIAL_BEARING_INNER_RING",
"children": [
{
"id": "330aa09d-60fb-40d7-a190-64264b3d44b7",
"type": "IDO_LOADCONTAINER",
"children": [
{
"id": "03036040-fc1a-4e52-8a69-d658e18a8d4a",
"type": "IDO_DISPLACEMENT",
"children": [],
"childList": "DISPLACEMENT",
"properties": [
{
"name": "IDCO_IDENTIFICATION",
"value": "03036040-fc1a-4e52-8a69-d658e18a8d4a"
},
{
"name": "IDCO_DESIGNATION",
"value": "Displacement 1"
}
],
"position": 1,
"order": 1,
"support_vector": {
"x": -201.3,
"y": 0,
"z": -229.8
},
"u_axis_vector": {
"x": 1,
"y": 0,
"z": 0
},
"w_axis_vector": {
"x": 0,
"y": 0,
"z": 1
},
"shaftSystemId": "ab7fbf37-17bb-4e60-a543-634571a0fd73",
"role": "_none_"
},
{
"id": "485f5bf4-fb97-415b-8b42-b46e9be080da",
"type": "IDO_CUMULATED_LOAD",
"children": [],
"childList": "CUMULATEDLOAD",
"properties": [
{
"name": "IDCO_IDENTIFICATION",
"value": "485f5bf4-fb97-415b-8b42-b46e9be080da"
},
{
"name": "IDCO_DESIGNATION",
"value": "Cumulated load 1"
},
{
"name": "IDCO_X",
"value": 0
},
{
"name": "IDCO_Y",
"value": 0
},
{
"name": "IDCO_Z",
"value": 0
}
],
"position": 2,
"order": 1,
"support_vector": {
"x": -201.3,
"y": 0,
"z": -229.8
},
"u_axis_vector": {
"x": 1,
"y": 0,
"z": 0
},
"w_axis_vector": {
"x": 0,
"y": 0,
"z": 1
},
"shaftSystemId": "ab7fbf37-17bb-4e60-a543-634571a0fd73",
"role": "_none_"
}
],
"childList": "LOADCONTAINER",
"properties": [
{
"name": "IDCO_IDENTIFICATION",
"value": "330aa09d-60fb-40d7-a190-64264b3d44b7"
},
{
"name": "IDCO_DESIGNATION",
"value": "Load container 1"
},
{
"name": "IDLC_LOAD_DISPLACEMENT_COMBINATION",
"value": "LOAD_MOMENT"
},
{
"name": "IDLC_TYPE_OF_MOVEMENT",
"value": "LB_ROTATING"
},
{
"name": "IDLC_NUMBER_OF_ARRAY_ELEMENTS",
"value": 20
}
],
"position": 1,
"order": 1,
"support_vector": {
"x": -201.3,
"y": 0,
"z": -229.8
},
"u_axis_vector": {
"x": 1,
"y": 0,
"z": 0
},
"w_axis_vector": {
"x": 0,
"y": 0,
"z": 1
},
"shaftSystemId": "ab7fbf37-17bb-4e60-a543-634571a0fd73",
"role": "_none_"
},
{
"id": "3258d217-e6e4-4a5c-8677-ae1fca26f21e",
"type": "IDO_RACEWAY",
"children": [],
"childList": "RACEWAY",
"properties": [
{
"name": "IDCO_IDENTIFICATION",
"value": "3258d217-e6e4-4a5c-8677-ae1fca26f21e"
},
{
"name": "IDCO_DESIGNATION",
"value": "Raceway 1"
},
{
"name": "IDRCW_UPPER_DEVIATION_RACEWAY_DIAMETER",
"value": 0
},
{
"name": "IDRCW_LOWER_DEVIATION_RACEWAY_DIAMETER",
"value": 0
},
{
"name": "IDRCW_PROFILE_OFFSET",
"value": 0
},
{
"name": "IDRCW_PROFILE_ANGLE",
"value": 0
},
{
"name": "IDRCW_PROFILE_CURVATURE_RADIUS",
"value": 0
},
{
"name": "IDRCW_PROFILE_CENTER_POINT_OFFSET",
"value": 0
},
{
"name": "IDRCW_PROFILE_NUMBER_OF_WAVES",
"value": 0
},
{
"name": "IDRCW_PROFILE_AMPLITUDE",
"value": 0
},
{
"name": "IDRCW_PROFILE_POSITION_OF_FIRST_WAVE",
"value": 0
},
Bug
First of all, replace the value variable's name by something else, because you have a value variable as the method argument and another value variable with the same name when iterating over the dictionary:
for key, value in search_dict.iteritems(): # <-- REPLACE value TO SOMETHING ELSE LIKE val
Otherwise you will have bugs, because the value from the dictionary is the new value which you will insert. But if you iterate like for key, val in then you can actually use the outer value variable.
Adding The Value Pair
It seems id is a key inside your search_dict, but reading your JSON file your search_dict may have several nested lists like properties and/or children, so it depends on where you want to add the new pair.
If you want to add it to the same dictionary where your id is:
if key == "id":
if value == IDCO:
print("FOUND IDCO IN JSON: " + value +"\n")
search_dict[name] = value
Result:
{
"id": "3258d217-e6e4-4a5c-8677-ae1fca26f21e",
"type": "IDO_RACEWAY",
"children": [],
"childList": "RACEWAY",
"<new name>": "<new value>",
"properties": [
{
"name": "IDCO_IDENTIFICATION",
"value": "3258d217-e6e4-4a5c-8677-ae1fca26f21e"
},
If you want to add it to the children or properties list inside the dictionary where id is:
if key == "id":
if value == IDCO:
print("FOUND IDCO IN JSON: " + value +"\n")
if search_dict.has_key("properties"): # you can swap "properties" to "children", depends on your use case
search_dict["properties"].append({"name": name, "value": value}) # a new dictionary with 'name' and 'value' keys
Result:
{
"id": "3258d217-e6e4-4a5c-8677-ae1fca26f21e",
"type": "IDO_RACEWAY",
"children": [],
"childList": "RACEWAY",
"properties": [
{
"name": "IDCO_IDENTIFICATION",
"value": "3258d217-e6e4-4a5c-8677-ae1fca26f21e"
},
{
"name": "<new name>",
"value": "<new value>"
},

folder structure to json with python(unicode)

This program creates a folder/file structure in json
#!/usr/bin/env python
import os
import errno
import json
import sys
def path_hierarchy(path):
hierarchy = {
'type': 'folder',
'name': os.path.basename(path),
'path': path,
}
try:
hierarchy['children'] = [
path_hierarchy(os.path.join(path, contents))
for contents in os.listdir(path)
]
except OSError as e:
if e.errno != errno.ENOTDIR:
raise
hierarchy['type'] = os.path.splitext(path)[1]
if hierarchy['type'] == "":
hierarchy['type'] = "Unknown"
return hierarchy
if __name__ == '__main__':
try:
directory = sys.argv[1]
except IndexError:
directory = os.getcwd()
fo = open("output.json", "w")
fo.write(json.dumps(path_hierarchy(directory), indent=2, sort_keys=False,))
fo.close()
It is actually working but a can't make it work with Greek and Japanesse characters. This is the output of the file.Is it an encoding issue or is it something with the json class in python. I use python3 so everything should be unicode but still...
{
"children": [
{
"children": [
{
"name": ".name",
"type": "Unknown",
"path": "I:\\Development\\Python\\JsonFileStruct\\.idea\\.name"
},
{
"name": "encodings.xml",
"type": ".xml",
"path": "I:\\Development\\Python\\JsonFileStruct\\.idea\\encodings.xml"
},
{
"name": "JsonFileStruct.iml",
"type": ".iml",
"path": "I:\\Development\\Python\\JsonFileStruct\\.idea\\JsonFileStruct.iml"
},
{
"name": "misc.xml",
"type": ".xml",
"path": "I:\\Development\\Python\\JsonFileStruct\\.idea\\misc.xml"
},
{
"name": "modules.xml",
"type": ".xml",
"path": "I:\\Development\\Python\\JsonFileStruct\\.idea\\modules.xml"
},
{
"name": "workspace.xml",
"type": ".xml",
"path": "I:\\Development\\Python\\JsonFileStruct\\.idea\\workspace.xml"
}
],
"name": ".idea",
"type": "folder",
"path": "I:\\Development\\Python\\JsonFileStruct\\.idea"
},
{
"name": "main.py",
"type": ".py",
"path": "I:\\Development\\Python\\JsonFileStruct\\main.py"
},
{
"name": "output.json",
"type": ".json",
"path": "I:\\Development\\Python\\JsonFileStruct\\output.json"
},
{
"name": "second.py",
"type": ".py",
"path": "I:\\Development\\Python\\JsonFileStruct\\second.py"
},
{
"children": [
{
"name": "\u03ba\u03b1\u03bb\u03cc\u03c0\u03b1\u03b9\u03b4\u03bf.json",
"type": ".json",
"path": "I:\\Development\\Python\\JsonFileStruct\\\u03ba\u03b1\u03ba\u03cc\u03c0\u03b1\u03b9\u03b4\u03bf\\\u03ba\u03b1\u03bb\u03cc\u03c0\u03b1\u03b9\u03b4\u03bf.json"
}
],
"name": "\u03ba\u03b1\u03ba\u03cc\u03c0\u03b1\u03b9\u03b4\u03bf",
"type": "folder",
"path": "I:\\Development\\Python\\JsonFileStruct\\\u03ba\u03b1\u03ba\u03cc\u03c0\u03b1\u03b9\u03b4\u03bf"
},
{
"name": "\u03ba\u03b1\u03bb\u03cc\u03c0\u03b1\u03b9\u03b4\u03bf.json",
"type": ".json",
"path": "I:\\Development\\Python\\JsonFileStruct\\\u03ba\u03b1\u03bb\u03cc\u03c0\u03b1\u03b9\u03b4\u03bf.json"
}
],
"name": "JsonFileStruct",
"type": "folder",
"path": "I:\\Development\\Python\\JsonFileStruct"
}

Categories

Resources