拆分值并指定键

时间:2017-03-30 19:19:39

标签: python

我有一个json数组,其中包含long和lat值,并且字段为空。我试图弄清楚一个python脚本循环遍历数组并将它们分成long和lat键。

[
  {
    "Shape": "(47.630880207000075, -122.37391463199998)"
  },
  {
    "Shape": ""
  },
  {
    "Shape": "(47.70118823100006, -122.38447021399998)"
  }
]

所需的输出:

[
  {
    "Long": "47.630880207000075",
    "Lat": "-122.37391463199998"

  },
  {
     "Long": "",
    "Lat": ""
  },
  {
   "Long": "47.70118823100006",
    "Lat": "-122.38447021399998"
  }
]

到目前为止,我已经将CSV转换为JSON并且正在计算出正则表达式以循环通过它..代码到目前为止:

导入csv

import json

csvfile = open('geoloc.csv', 'r')
jsonfile = open('file.json', 'w')

# fieldnames = ("S")
reader = csv.DictReader( csvfile)
out = json.dumps( [ row for row in reader ], sort_keys=True, indent=4 )
jsonfile.write(out)

2 个答案:

答案 0 :(得分:2)

可能很容易使用ast.literal_eval将其转换为tuplere,例如:

In [1]:
import ast
def tuple_convert(t):
    return ast.literal_eval(t) if t else ('', '')

keys = ['Long', 'Lat']
[dict(zip(keys, tuple_convert(d['Shape']))) for d in data]

Out[1]:
[{'Lat': -122.37391463199998, 'Long': 47.630880207000075},
 {'Lat': '', 'Long': ''},
 {'Lat': -122.38447021399998, 'Long': 47.70118823100006}]

答案 1 :(得分:0)

假设您的 AND SUBSTR(TB1.YEARF, 1, 4) = SUBSTR(TB2.YEARF, 1, 4) AND 已加载到json

d

编辑: 为了使其更具可读性:

>>> l = [{"Long": c['Shape'][1:-1].split(',')[0].strip() if len(c['Shape']) > 0 else '',
"Lat": c['Shape'][1:-1].split(',')[1].strip() if len(c['Shape']) > 0 else ''} for c in d]
>>> l
[{'Lat': '-122.37391463199998', 'Long': '47.630880207000075'},
 {'Lat': '', 'Long': ''},
 {'Lat': '-122.38447021399998', 'Long': '47.70118823100006'}]