遍历并加入json中的值

时间:2019-01-23 18:58:28

标签: python json

我有一个json文件,我试图对其进行循环访问以加入内部的文件路径,但是我仍然遇到问题:

{
  "files": [
    {
      "name": "Mississippi",
      "folder": "H:\\Data\\Mississippi",
      "zFeatures": [
        {
          "name": "Land_Use",
          "file": "MS_LandUse.shp",
            }
          ]
        }
      ]
    }

在这种情况下,我想将file加入folder,所以我的输出是:"H:\\Data\\Mississippi\\MS_LandUse.shp"。我确实还有数百个其他文件也需要加入,因此我需要遍历此json。

我尝试了自上而下的迭代,但是失败了

with open("filoc.json", "r") as i:
    filoc = json.load(i)

for files in filoc['files']:
    for folder in files['folder']:
        for zFeatures in files['zFeatures']:
        #This is where I'm stumped, I feel like I'm already doing it wrong.

2 个答案:

答案 0 :(得分:3)

您正在做某事。遗憾的是您没有确切说明问题所在。首先,让我更正JSON数据(它已损坏):

{
  "files": [
    {
      "name": "Mississippi",
      "folder": "H:\\Data\\Mississippi",
      "zFeatures": [
        {
          "name": "Land_Use",
          "file": "MS_LandUse.shp"
        }
      ]
    }
  ]
}

然后,您可以将os.path.joinos.path.abspath结合起来,并按照以下方式进行操作,以确保路径正确:

import os, json

with open("test.json", "r") as i:
    filoc = json.load(i)

for file_info in filoc['files']:
    print(os.path.abspath(os.path.join(file_info['folder'], file_info['zFeatures'][0]['file'])))

这假设zFeatures下只有一个文件。如果有多个,请执行以下操作:

for file_info in filoc['files']:
    for f_obj in file_info['zFeatures']:
        print(...(file_info['zFeatures'][f_obj]['file']))

但是我假设这个blob是每个文件的。

最后,请注意os.path.abspath-如果在Linux计算机上传递了Windows路径,它将生成一个奇怪的路径。如果路径是混合的,则跳过abspath(),并希望路径没有混合或正确无误。

答案 1 :(得分:1)

将示例json输入文件更改为有效JSON后:

$ aws iam upload-server-certificate --server-certificate-name ExampleCertificate
                                    --certificate-body file://Certificate.pem
                                    --certificate-chain file://CertificateChain.pem
                                    --private-key file://PrivateKey.pem

这可能是您想要做的最简单的方法:

An error occurred (MalformedCertificate) when calling the UploadServerCertificate 
operation:

Certificate body is invalid. The body must not contain a private key.

打印此处理示例输入文件: { "files": [ { "name": "Mississippi", "folder": "H:\\Data\\Mississippi", "zFeatures": [ { "name": "Land_Use", "file": "MS_LandUse.shp" } ] } ] }

由于可能存在多个import json import os with open("filoc.json", "r") as inp: filoc = json.load(inp) for file_metadata in filoc['files']: folder = file_metadata['folder'] filename = file_metadata['zFeatures'][0]['file'] print(os.path.join(folder, filename)) 文件,因此您可能希望/需要在H:\Data\Mississippi\MS_LandUse.shp循环内嵌套另一个"zFeatures"循环来分别处理每个文件。这就是我的意思:

for