简体   繁体   English

将类似JSON的对象转换为JSON

[英]Converting JSON-like object to JSON

I have a JSON file that was filtered and lost the original structure. 我有一个已过滤并丢失原始结构的JSON文件。 Each line of the file looks like this: 文件的每一行如下所示:

{u'spec1': {u'property1': u'12345', u'property2': 1234}, u'spec2': {u'property3': u'98754', u'property4': u'val1'}}

json.loads doesn't work and ast.literal_eval doesn't work. json.loads不起作用,而ast.literal_eval不起作用。 I guess I have 2 issues: remove unicode and change ' to ". Can anyone provide some pointers on where to start? 我猜我有2个问题:删除unicode并将'更改为“。有人可以提供有关从何处开始的指针吗?

Assuming you are using Python 2.X. 假设您正在使用Python2.X。

json.loads takes a str or unicode as its param. json.loadsstrunicode作为其参数。 The string you give is not a valid json string. 您提供的字符串不是有效的json字符串。 So we should do some pre-cooking work. 因此,我们应该做一些预烹饪工作。

import re, json

json_str = """{u'spec1': {u'property1': u'12345', u'property2': 1234}, u'spec2': {u'property3': u'98754', u'property4': u'val1'}}"""
json_str = json_str.replace("\'", "\"")
json_str = re.sub(r"u\"", "\"", json_str)

json_dict = json.loads(json_str)

Then the json_dict will be a dictionary inflated from your json string. 然后json_dict将是从您的json字符串json_dict的字典。

Looks like this works (in Python3): 看起来像这样(在Python3中):

$ python3.4
Python 3.4.0 (default, Jun 19 2015, 14:20:21) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> j = """{u'spec1': {u'property1': u'12345', u'property2': 1234}, u'spec2': {u'property3': u'98754', u'property4': u'val1'}}"""
>>> json.loads(j.replace("'","\"").replace('u"','"'))
{'spec1': {'property1': '12345', 'property2': 1234}, 'spec2': {'property4': 'val1', 'property3': '98754'}}

As you can see, I've replaced both ' to " chars, and (thus came) u" to " patterns. 如您所见,我已经将'替换为“ chars,并将(因此来了)u”替换为“模式。

Hope this helps. 希望这可以帮助。

a. 一种。

Here is my take (Python 2.7). 这是我的看法(Python 2.7)。

import StringIO
import ast
file = u"""{u'spec1': {u'property1': u'12345', u'property2': 1234}, u'spec2': {u'property3': u'98754', u'property4': u'val1'}}
{u'spec2': {u'property1': u'12345', u'property2': 1234}, u'spec3': {u'property3': u'98754', u'property4': u'val1'}}
{u'spec4': {u'property1': u'12345', u'property2': 1234}, u'spec2': {u'property5': u'98754', u'property4': u'val1'}}
{u'spec6': {u'property1': u'12345', u'property2': 1234}, u'spec2': {u'property7': u'98754', u'property4': u'val1'}}
"""
buffer = StringIO.StringIO(file)
lines = buffer.readlines()
dicts = []
for line in lines:
    dicts.append(ast.literal_eval(line))
print dicts

Don't look at StringIO , it's there to emulate file-reading. 不用看StringIO ,它在那里可以模拟文件读取。 What I'm proposing is to read the file by line and do literal_eval by line. 我建议的是逐行读取文件,然后逐行执行literal_eval

For me it was the only way to make it work without errors. 对我而言,这是使其无错误运行的唯一方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM