在变量位置向Python字典添加条目

时间:2019-03-08 09:30:14

标签: python json dictionary

我有一个看起来像这样的json文件(为了简化起见,我已经做了很多工作,所以请忽略其中缺少的括号):

{
  "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"
                          }
                        ]

我想向其中添加条目,但问题是我要添加的位置不一致。 id键将更改,例如有时我可能想将条目添加到"id": "ab7fbf37-17bb-4e60-a543-634571a0fd73",而另一个我可能想将条目添加到"id": "0b3e695b-6028-43af-874d-4826ab60dd3f"

我所执行的代码循环遍历另一个文件,每次找到ID和属性名称时,它都会存储ID,名称和值。

我当前使用的代码是:

    import os
    import json
    import shutil
    import re
    import fileinput

    #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]","IDSU_FY[0]","IDSU_FZ[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])
                        print(name)
                        print(value)
                        #json file editing        
                        with open(fileNameThree , "r+") as json_data:
                            python_obj = json.load(json_data)

                        new_element = [{"name": name, "value":value}]

                        python_obj['"id": "485f5bf4-fb97-415b-8b42-b46e9be080da"']

                        #foreach in new_elements:
                            #data['rootObject']['children'][0]['properties'].append(each)


print('Processed {} lines in file {}'.format(n , fileName))

    for modelFolder in folders:
        processModelFolder(modelFolder)

是否有任何明显的方法可以动态更改放置新条目的位置?我很难过,因为它的缩进级别可能会改变。

**更新代码:

import os
import json
import shutil
import re
import fileinput

#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]","IDSU_FY[0]","IDSU_FZ[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])
                    key = os.path.join('"id": "'+IDCO+'"')
                    print(key)
                    print(name)
                    print(value)
                    #json file editing        
                    with open(fileNameThree , "r+") as json_data:
                        python_obj = json.load(json_data)

                    new_element = [{"name": name, "value":value}]
                    print("NEW ELEMENT:")
                    print(new_element)
                    for each in new_element:
                        children = {x['id']: x for x in python_obj['rootObject']['children']}
                        children[IDs]['properties'].append(each)

                        python_obj['rootObject']['children'] = [x for _, x in children.items()]
                    with open(fileNameThree , "w") as json_data:
                       json.dump(python_obj, json_data, indent = 3)





























            print('Processed {} lines in file {}'.format(n , fileName))

for modelFolder in folders:
    processModelFolder(modelFolder)

1 个答案:

答案 0 :(得分:0)

您可以将'children'列表转换成字典。

children = {x['id']: x for x in data['rootObject']['children']}

或者如果您的订单很重要:

od = OrderedDict()
for child in children:
    od[child['id']] = child

然后基于id进行插入

children[<<id here>>]['properties'].append(each)

然后将字典转换回列表

data['rootObject']['children'] = [x for _, x in children.items()]