-
Notifications
You must be signed in to change notification settings - Fork 2
/
wpXML2json.coffee
93 lines (61 loc) · 2.13 KB
/
wpXML2json.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# convert wordpress dump to json
fs = require 'fs',
async = require 'async'
xml2js = require 'xml2js'
parser = new xml2js.Parser()
# map function f to obj recursively
map_obj = (f,obj) ->
res = {}
for key,value of obj
value = f value
res[key] = value unless value == ""
return res
simplify_arrays = (obj) ->
if obj instanceof Array
return simplify_arrays obj[0] if obj.length == 1
return obj.map simplify_arrays
return map_obj(simplify_arrays,obj) if typeof obj is 'object'
return obj
flatten = (obj) ->
data = {}
collect_key_value_pairs = (path,obj) ->
if obj instanceof Array
if path.length > 0
path += "."
for value,index in obj
collect_key_value_pairs path+index, value
return
if typeof obj is 'object'
if path.length > 0
path += "."
for key,value of obj
collect_key_value_pairs path+key, value,
return
data[path]=obj
collect_key_value_pairs '',obj
return data
l = (a...) -> console.log a
convert_xml_file_to_array = (filename,cb) ->
fs.readFile filename, (err, data) ->
parser.parseString data, (err, result) ->
return cb err, null if err
result = simplify_arrays result
items = result.rss.channel.item
res = []
for item in items
item.categories = ( "#{c.$.domain}/#{c.$.nicename}" for c in item.category ).join " "
delete item.category
for meta in item["wp:postmeta"]
key = meta["wp:meta_key"]
value = meta["wp:meta_value"]
item["wp:postmeta:"+key] = value
delete item["wp:postmeta"]
# delete item.guid
# delete item["wp:postmeta:_url_crea"]
res.push flatten item
cb null, res
main = () ->
convert_xml_file_to_array __dirname + '/data.xml', (err,items) ->
# add_whois items, "wp:postmeta:_url_crea", (err,items) ->
console.log JSON.stringify items, null, 2
main()