如何遍历整个JSON文件

时间:2015-12-03 22:28:14

标签: python json python-2.7

我写了这段代码来解析JSON及其罚款。它只是停止通过文件生成输出部分。我做了len(数据),它返回6,这是它返回的项目数。但是当我确实产生数据时,会打印所有7000多行。那么如何更改此代码以便遍历整个文件?另外,如何从'路径返回最小和最大坐标。列出?

import os
import json
import pprint as p

def jSonYield():
    n = 0
    os.chdir('C:\Users\U2970\Documents\ArcGIS')
    with open('new_corrs_shapy_FeaturesToJS.json') as datafile:
        data = json.loads(datafile.read())
    datafile.close()
    for line in data:
        n = n + 1
        corr =  data['features'][n]['attributes']['CORRIDOR_C']
        trf =  data['features'][n]['attributes']['TRFPOST']
        frf =  data['features'][n]['attributes']['FRFPOST']
        coords =  data['features'][n]['geometry']['paths']
        yield corr,frf,trf,coords


gen = jSonYield()
for line in gen:
    p.pprint(line)

以下是JSON数据的示例位:

{u'attributes': {u'CORRIDOR_C': u'C000896N',
                            u'FID': 2,
                            u'FRFPOST': 0,
                            u'OBJECTID': 4,
                            u'TRFPOST': 0.392},
            u'geometry': {u'paths': [[[682789.8871999979,
                                       173265.5223999992],
                                      [682791.4069999978,
                                       173246.46599999815],
                                      [682796.4217000008,
                                       172938.67540000007],
                                      [682797.1617999971,
                                       172899.74130000174],
                                      [682798.8253000006,
                                       172790.22789999843],
                                      [682802.0223999992,
                                       172634.72960000113]]]}},  

1 个答案:

答案 0 :(得分:1)

所以,回顾一下评论:

第一个问题:

customer.Uid = Guid.NewGuid()
// set other properties
myCustomerService.Insert(myCompanyFile, myobCustomerContact, myCredentials );
myobCustomerContact = myCustomerService.Get(myCompanyFile, myobCustomerContact.UID,myCredentials);   

for line in data: 是一个包含键的词典,而不是"行"。

另外,如果您使用data,则不需要with open() as datafile:。这会在datafile.close()缩进之外自动发生。

为了迭代字典中的所有键和值(with是什么),你需要做类似的事情

data

不确定for key, val in data.items(): 是什么,但如果这对您有用,那就太棒了!