如何将json.loads解析为字符串转换为字典python

问题描述 投票:-1回答:1

标题可能会引起误解。我有一个要加载的json文件,看起来像这样:

{"parent": [
  {"venue": "SE", 
  "city": "some name", 
  "Rating": 2, 
  "location": {"x": 100.0, "y": 1.0}, 
  "pubMillis": 1581373546000}
  ], 
"startTime": "2020-02-12 00:00:00:000", 
"endTime": "2020-02-12 00:01:00:000"
}
{"parent": [
  {"venue": "PP", 
  "city": "some name 2", 
  "Rating": 2, 
  "location": {"x": 101.0, "y": 2.0}, 
  "pubMillis": 1581373546000}
  ], 
"startTime": "2020-02-12 00:00:00:000", 
"endTime": "2020-02-12 00:05:00:000"
}

每个parent键都由\n隔开,如图所示。

我想读这,这是我的代码:

with open('filename.json', 'r') as content_file:
    content = content_file.read()
records = json.loads(json.dumps(content))

print(type(records)) #return as str

如果我写records = json.loads(content),将出现以下错误:

json.decoder.JSONDecodeError:额外数据:第2行第1列(字符517)

因此,json.loads(json.dumps(content))似乎有效。但是,我了解到转换dumps-> loads将返回为str而不是dict。因此,由于它们位于字符串中,因此无法访问诸如records["parents"]["location"]之类的项目。

因此,如何通过将str转换为dict来访问内部项目?

python json dictionary
1个回答
0
投票

这里是问题

似乎您有多个子文件,{.....}是一个json

OR

那些({.....})应该在数组中……我在数组方法下面显示了

a = '''{"parent": [
  {"venue": "SE", 
  "city": "some name", 
  "Rating": 2, 
  "location": {"x": 100.0, "y": 1.0}, 
  "pubMillis": 1581373546000}
  ], 
"startTime": "2020-02-12 00:00:00:000", 
"endTime": "2020-02-12 00:01:00:000"
}
{"parent": [
  {"venue": "PP", 
  "city": "some name 2", 
  "Rating": 2, 
  "location": {"x": 101.0, "y": 2.0}, 
  "pubMillis": 1581373546000}
  ], 
"startTime": "2020-02-12 00:00:00:000", 
"endTime": "2020-02-12 00:05:00:000"
}'''
a = [i.strip() if i.strip()!='}' else i.strip()+',' for i in a.split('\n') ]
a = '\n'.join(a)
a= '[\n'+a[:-1]+'\n]'
import json 
a=json.loads(a) 
print(a)
[{'endTime': '2020-02-12 00:01:00:000',
  'parent': [{'Rating': 2,
    'city': 'some name',
    'location': {'x': 100.0, 'y': 1.0},
    'pubMillis': 1581373546000,
    'venue': 'SE'}],
  'startTime': '2020-02-12 00:00:00:000'},
 {'endTime': '2020-02-12 00:05:00:000',
  'parent': [{'Rating': 2,
    'city': 'some name 2',
    'location': {'x': 101.0, 'y': 2.0},
    'pubMillis': 1581373546000,
    'venue': 'PP'}],
  'startTime': '2020-02-12 00:00:00:000'}]

这是如何获取数据的方法

a=json.loads(a) 
#print(a)
print(a[0]['parent'][0]['location'])
{'x': 100.0, 'y': 1.0}

如果您想将文件读入内存

a = "".join([i for i in open('yourFileLocation','r').readlines()])

现在您在内存中以多行字符串的形式存在a

© www.soinside.com 2019 - 2024. All rights reserved.