signmem 发表于 2014-11-12 15:10

数据格式转换求助

| net.if.in                  | hh-yun-compute-131092.vclound.com |                6592 |
| net.if.in                  | hh-yun-compute-131092.vclound.com |                  112 |
| net.if.out                  | hh-yun-compute-131092.vclound.com |                5512 |
| net.if.out                  | hh-yun-compute-131092.vclound.com |                     0 |
| vm.memory.size | hh-yun-compute-131092.vclound.com | 134131691520 |
| net.if.in                  | hh-yun-compute-131093.vclound.com |               6840 |
| net.if.in                  | hh-yun-compute-131093.vclound.com |                   24 |
| net.if.out                  | hh-yun-compute-131093.vclound.com |               5552 |
| net.if.out                  | hh-yun-compute-131093.vclound.com |                     0 |
| vm.memory.size | hh-yun-compute-131093.vclound.com | 134133485568 |
| net.if.in                  | hh-yun-compute-131094.vclound.com |               6608 |
| net.if.in                  | hh-yun-compute-131094.vclound.com |                   88 |
| net.if.out                  | hh-yun-compute-131094.vclound.com |               5440 |
| net.if.out                  | hh-yun-compute-131094.vclound.com |                     0 |
| vm.memory.size | hh-yun-compute-131094.vclound.com | 134134104064 |
| net.if.in                  | hh-yun-compute-131095.vclound.com |                6656 |
| net.if.in                  | hh-yun-compute-131095.vclound.com |                   48 |
| net.if.out                  | hh-yun-compute-131095.vclound.com |                5440 |
| net.if.out                  | hh-yun-compute-131095.vclound.com |                     0 |
| vm.memory.size | hh-yun-compute-131095.vclound.com | 134136803328 |
+-------------------------------+-------------------------------------------+-----------------+


从数据中获取上面的内容后,我是否可以把他们转换成为 json 格式?


data:{'hh-yun-compute-131092.vclound.com':{'net.if.in':'6592','net.if.in':'112','net.if.out':'5512','net.if.out':'0','vm.memory.size ':'134131691520'}, hh-yun-compute-131093.vclound.com:{'net.if.in':'6592','net.if.in':'112','net.if.out':'5512','net.if.out':'0','vm.memory.size ':'134131691520'} ........}

reyleon 发表于 2014-11-12 18:44

#!/usr/bin/python
# -*- coding: utf-8 -*-

import json, fileinput, sys, re
if len(sys.argv) != 2:
    print "usage: %s " % sys.argv
    sys.exit(1)

d = dict()
for line in fileinput.input(sys.argv):
    l = [ r.strip() for r in line.strip().split("|")]
    if not d.has_key(l): d] = dict()
    d]] = l
print "data:"+json.dumps(d)

signmem 发表于 2014-12-29 10:49

感谢, 使用 JSON_DECODE 更加简单
页: [1]
查看完整版本: 数据格式转换求助