gpt4 book ai didi

python - 如何解析 Apple 的 IAP 收据格式错误的 JSON?

转载 作者:行者123 更新时间:2023-11-28 20:26:34 25 4
gpt4 key购买 nike

我得到了 JSON from apple像这样

{
"original-purchase-date-pst" = "2012-06-28 02:46:02 America/Los_Angeles";
"original-transaction-id" = "1000000051960431";
"bvrs" = "1.0";
"transaction-id" = "1000000051960431";
"quantity" = "1";
"original-purchase-date-ms" = "1340876762450";
"product-id" = "com.x";
"item-id" = "523404215";
"bid" = "com.x";
"purchase-date-ms" = "1340876762450";
"purchase-date" = "2012-06-28 09:46:02 Etc/GMT";
"purchase-date-pst" = "2012-06-28 02:46:02 America/Los_Angeles";
"original-purchase-date" = "2012-06-28 09:46:02 Etc/GMT";
}

这不是 JSON我们知道。在 JSON 中明确定义了

Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

我什至如何在 python 的 json(或 simplejson)模块中解析它?

json 只支持 json.dumps() 中的separatorsjson.loads() 中不支持,在 simplejson/decoder.py 中,def JSONObject() 具有硬编码分隔符 :, .

我能做什么?编写我自己的解析器?

最佳答案

确实有点乱。一个快速的解决方法是用正则表达式替换有问题的分隔符:

line = re.compile(r'("[^"]*")\s*=\s*("[^"]*");')
result = line.sub(r'\1: \2,', result)

您还需要删除最后一个逗号:

trailingcomma = re.compile(r',(\s*})')
result = trailingcomma.sub(r'\1', result)

通过这些操作,示例加载为 json:

>>> import json, re
>>> line = re.compile('("[^"]*")\s*=\s*("[^"]*");')
>>> result = '''\
... {
... "original-purchase-date-pst" = "2012-06-28 02:46:02 America/Los_Angeles";
... "original-transaction-id" = "1000000051960431";
... "bvrs" = "1.0";
... "transaction-id" = "1000000051960431";
... "quantity" = "1";
... "original-purchase-date-ms" = "1340876762450";
... "product-id" = "com.x";
... "item-id" = "523404215";
... "bid" = "com.x";
... "purchase-date-ms" = "1340876762450";
... "purchase-date" = "2012-06-28 09:46:02 Etc/GMT";
... "purchase-date-pst" = "2012-06-28 02:46:02 America/Los_Angeles";
... "original-purchase-date" = "2012-06-28 09:46:02 Etc/GMT";
... }
... '''
>>> line = re.compile(r'("[^"]*")\s*=\s*("[^"]*");')
>>> trailingcomma = re.compile(r',(\s*})')
>>> corrected = trailingcomma.sub(r'\1', line.sub(r'\1: \2,', result))
>>> json.loads(corrected)
{u'product-id': u'com.x', u'purchase-date-pst': u'2012-06-28 02:46:02 America/Los_Angeles', u'transaction-id': u'1000000051960431', u'original-purchase-date-pst': u'2012-06-28 02:46:02 America/Los_Angeles', u'bid': u'com.x', u'purchase-date-ms': u'1340876762450', u'original-transaction-id': u'1000000051960431', u'bvrs': u'1.0', u'original-purchase-date-ms': u'1340876762450', u'purchase-date': u'2012-06-28 09:46:02 Etc/GMT', u'original-purchase-date': u'2012-06-28 09:46:02 Etc/GMT', u'item-id': u'523404215', u'quantity': u'1'}

它也应该处理嵌套映射。不过,这确实假设值本身没有转义的 " 引号。如果有,您无论如何都需要一个解析器。

关于python - 如何解析 Apple 的 IAP 收据格式错误的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11242667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com