将cppheaderparser输出保存为有效的json

时间:2015-06-05 21:18:41

标签: json python-2.7

python程序 http://sourceforge.net/projects/cppheaderparser/ 可以解析c ++头文件并将信息(关于类等)存储在python词典中。

使用包含的示例程序readSampleClass.py和

data_string = ( repr(cppHeader) )
with open('data.txt', 'w') as outfile:
    json.dumps(data_string,outfile)

它保存了输出但是json无效 它使用单引号,而不是双引号,键引用部分没有引用。

输出样本:(减少)

{'enums': [], 'variables': [], 'classes': 
    {'SampleClass': 
        {'inherits': [], 'line_number': 8, 'declaration_method': 'class', 'typedefs': 
            {'public': [], 'private': [], 'protected': []
            }, 'abstract': False, 'parent': None,'parent': None, 'reference': 0, 'constant': 0, 'aliases': [], 'raw_type': 'void', 'typedef': None, 'mutable': False
        }], 'virtual': False, 'rtnType': 'int', 'returns_class': False, 'name': 'anotherFreeFunction', 'constructor': False, 'inline': False, 'returns_pointer': 0, 'defined': False
     }]
}

所以问题是:

如何让它使用双引号而不是单引号,我怎样才能使它引用值部分。像样本中的假。

我认为有可能作为cppheaderparser的创建者写道 关于json.dumps(repr(cppHeader)) https://twitter.com/senexcanis/status/559444754166198272

为什么使用json lib,如果它是无效的jason?
这就是说我之前从未使用过python,它可能根本无法工作。

-update -

在一些json doc阅读之后,我放弃了json.dump,因为在这种情况下它似乎对输出无效。 我最终做了

data_string = ( repr(cppHeader) )
data_string = string.replace(data_string,'\'', '\"')
data_string = string.replace(data_string,'False', '\"False\"')
data_string = string.replace(data_string,'True', '\"True\"')
data_string = string.replace(data_string,'None', '\"None\"')
data_string = string.replace(data_string,'...', '')
with open('data.txt', 'w') as outfile:
    outfile.write (data_string)

给出有效的json - 至少对于我的测试c ++标题。

-update 2- cppheaderparse的创建者刚刚发布了一个新的2.6版本,可以编写CppHeaderParser.CppHeader("yourHeader.h").toJSON()来保存为json。

0 个答案:

没有答案