2014-11-03 127 views
0

我剛剛爲我的後端服務器開發了一個使用解析的iOS應用程序。我有完整的應用程序,並準備好去,並有大量的條目添加到解析後端,但是我已經提交了數據,直到現在還沒有意識到要加載包括我需要使用json的地理點的類。將CSV轉換爲JSON解決方案

Country,PostCode,State,Suburb,location/__type,location/latitude,location/longitude,locname,phone,streetaddress,website 
Australia,2000,NSW,Cronulla,GeoPoint,-33.935434,151.026887,Shop ABC,+61297901401,ABC Canterbury Road,http://www.123.com.au 

我需要這個格式轉換爲以下

{ "results": [ 
    { 
     "Country": "Australia", 
     "PostCode": "2000", 
     "State": "NSW", 
     "Suburb": 「Crounlla」, 
     "location": { 
      "__type": "GeoPoint", 
      "latitude": -33.935434, 
      "longitude": 151.026887 
     }, 
     "locname": "Shop ABC」, 
     "phone": "+123456」, 
     "streetaddress": 「ABC Canterbury Road", 
     "website": "http://www.123.com.au" 
    } 
] } 

我有幾千個條目,這樣你可以想像我不想要做的:我的數據文件的結構如下它手動。我只能訪問Mac,因此任何建議都需要Mac友好。我發現以前的答案由於地理數據而無法使用。

回答

2

您可以使用Python腳本(Mac是Python預安裝) 示例代碼:

#!/usr/bin/python 

import csv 
import json 


header = [] 
results = [] 
with open('data.csv', 'rb') as f: 
    reader = csv.reader(f) 
    for row in reader: 
     if len(header) > 0: 
      location = {} 
      datarow = {} 
      for key, value in (zip(header,row)): 
       if key.startswith('location'): 
        location[key.split('/')[1]] = value 
       else: 
        datarow[key] = value 
      datarow['location'] = location 
      results.append(datarow) 
     else: 
      header = row 

     print json.dumps(dict(results=results)) 
1

下面是使用jq的解決方案。

如果filter.jq包含以下濾波器

def parse: 
    [ 
     split("\n")[]      # split string into lines 
    | split(",")       # split data 
    | select(length>0)     # eliminate blanks 
    ] 
; 

def reformat: 
    [ 
     .[0] as $h      # headers 
    | .[1:][] as $v      # values 
    | [ [$h, $v]     
     | transpose[]      # convert array 
     | {key:.[0], value:.[1]}   # to object 
     ] | from_entries     # 
    | reduce (
      keys[]       # 
     | select(startswith("location/")) # move keys starting 
    ) as $k (       # with "location/" 
      .        # into a "location" object 
     ; setpath($k|split("/");.[$k]) # 
     | delpaths([[$k]])    # 
    ) 
    | .location.latitude |= tonumber  # convert "latitude" and 
    | .location.longitude |= tonumber  # "longitude" to numbers 
    ] 
; 

{ 
    results: (parse | reformat) 
} 

data包含樣本數據,則命令

$ jq -M -Rsr -f filter.jq data 

產生

{ 
    "results": [ 
    { 
     "Country": "Australia", 
     "PostCode": "2000", 
     "State": "NSW", 
     "Suburb": "Cronulla", 
     "locname": "Shop ABC", 
     "phone": "+61297901401", 
     "streetaddress": "ABC Canterbury Road", 
     "website": "http://www.123.com.au", 
     "location": { 
     "__type": "GeoPoint", 
     "latitude": -33.935434, 
     "longitude": 151.026887 
     } 
    } 
    ] 
} 
相關問題