[英]Parsing formatted JSON with Python
I want to parse JSON. 我想解析JSON。 Its ok if I write JSON in one line 如果我在一行中写JSON就可以了
json_input = '{ "rate_of_climbing": 18.4, "speed_factor": 520}'
But if I have JSON formated then parser does not work: 但是,如果我使用JSON格式,则解析器将不起作用:
json_input = '{
"rate_of_climbing": 18.4,
"speed_factor": 520
}'
How can I get JSON to read for formatted string? 如何获取JSON以读取格式化的字符串?
My full code: 我的完整代码:
import json
json_input = '{
"rate_of_climbing": 18.4,
"speed_factor": 520
}'
try:
decoded = json.loads(json_input)
print json.dumps(decoded, sort_keys=True, indent=4)
print "JSON parsing example: ", decoded['rate_of_climbing']
print "Complex JSON parsing example: ", decoded['speed_factor']
except (ValueError, KeyError, TypeError):
print "JSON format error"
Use '''triple-quoted string literals'''
(or """triple-quoted string literals"""
) if the string contains newlines. 如果字符串包含换行符,请使用'''triple-quoted string literals'''
(或"""triple-quoted string literals"""
)。
json_input = '''{
"rate_of_climbing": 18.4,
"speed_factor": 520
}'''
I think you can store these json data info a file; 我认为您可以将这些json数据信息存储在文件中;
then read all: 然后阅读全部:
json_data = ''.join([line.strip() for line in open('path to json file')])
then, 然后,
_data = json.loads(json_data)
json.dumps(_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.