我想解析JSON。如果我在一行中编写JSON,那就好了
json_input = '{ "rate_of_climbing": 18.4, "speed_factor": 520}'
但如果我编写了JSON,则解析器不起作用:
json_input = '{
"rate_of_climbing": 18.4,
"speed_factor": 520
}'
如何获取JSON以读取格式化字符串?
我的完整代码:
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"
答案 0 :(得分:6)
如果字符串包含换行符,请使用'''triple-quoted string literals'''
(或"""triple-quoted string literals"""
)。
json_input = '''{
"rate_of_climbing": 18.4,
"speed_factor": 520
}'''
答案 1 :(得分:0)
我认为您可以将这些json数据信息存储为文件;
然后阅读全部:
json_data = ''.join([line.strip() for line in open('path to json file')])
然后,
_data = json.loads(json_data)
json.dumps(_data)