在Python中解析两个JSON字符串 [英] Parse two JSON strings in Python

查看:323
本文介绍了在Python中解析两个JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

套接字接收JSON格式的字符串,并且可能接收多个字符串,这将导致变量包含如下内容:

A socket receives a JSON formatted string and might receive more than one which will result in a variable containing something like this:

{'a':'1','b':'44'}{'a':'1','b':'44'}

如您所见,它是一个变量中的多个JSON字符串.如何在Python中解码这些内容?

As you can see, it is multiple JSON strings in one variable. How can I decode these in Python?

我的意思是,Python中有没有办法将两个JSON字符串解码为数组,或者只是一种知道输出中可能有两个字符串的方式?

I mean, is there a way in Python to decode the two JSON strings into an array, or just a way to know there might be two strings in the output?

使用新行来分割它们不是一个好主意,因为数据实际上可能有新行.

Using new lines to split them is not a good idea as the data might actually have new lines.

推荐答案

您可以使用标准的JSON解析器,并利用当正确的JSON字符串后面有额外的数据时引发的描述性异常.

You can use the standard JSON parser and make use of the descriptive exception it throws when there is extra data behind the proper JSON string.

当前(即我的JSON解析器版本)抛出ValueError并显示如下消息:"Extra data: line 3 column 1 - line 3 column 6 (char 5 - 10)".

Currently (that is, my version of the JSON parser) throws a ValueError with a message looking like this: "Extra data: line 3 column 1 - line 3 column 6 (char 5 - 10)".

在这种情况下的数字正则表达式轻松地从消息中解析出该数字)提供信息其中解析失败.因此,如果遇到该异常,则可以解析原始输入的子字符串,即解析直到该字符之前的所有内容,然后(我递归地提出)解析其余的内容.

The number 5 in this case (you can parse that out of the message easily with a regular expression) provides the information where the parsing failed. So if you get that exception, you can parse a substring of your original input, namely everything up to the character before that, and afterwards (I propose recursively) parse the rest.

import json, re

def jsonMultiParse(s):
  try:
    return json.loads(s)
  except ValueError as problem:
    m = re.match(
      r'Extra data: line \d+ column \d+ - line \d+ column \d+ .char (\d+) - \d+.',
      problem.message)
    if not m:
      raise
    extraStart = int(m.group(1))
    return json.loads(s[:extraStart]), jsonMultiParse(s[extraStart:])

print jsonMultiParse('{}[{}]    \n\n["foo", 3]')

将打印:

({}, ([{}], [u'foo', 3]))

如果您更喜欢使用直元组而不是嵌套元组:

In case you prefer to get a straight tuple instead of a nested one:

    return (json.loads(s),)

    return (json.loads(s[:extraStart]),) + jsonMultiParse(s[extraStart:])

返回:

({}, [{}], [u'foo', 3])

这篇关于在Python中解析两个JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆