简体   繁体   English

如何将以下奇数字符串转换为python中的json?

[英]How to convert the following odd string into json in python?

How to convert this string into json in python? 如何在python中将此字符串转换为json?

>>> data = '[for: css=a[title="See LLCAutoSept files"]]'
>>> json.dumps(data)
'"[for: css=a[title=\\"See LLCAutoSept files\\"]]"'

I've tried using json.dumps(), however the output json is could not be validated on jsonlint.com 我尝试使用json.dumps(),但是无法在jsonlint.com上验证输出json

You are looking at the Python string representation. 您正在查看Python字符串表示形式。 It's valid Python code, containing valid JSON. 这是有效的Python代码, 包含有效的JSON。

Print the value: 打印值:

>>> imp
>>> data = '[for: css=a[title="See LLCAutoSept files"]]'
>>> print json.dumps(data)
"[for: css=a[title=\"See LLCAutoSept files\"]]"

JSONlint is using the older , stricter RFC 4627 that requires the top level to be an array or object, so it won't validate a JSON string. JSONlint使用的是更旧更严格的RFC 4627 ,它要求顶层是数组或对象,因此它不会验证JSON字符串。

However, Python's json.dumps() produces valid RFC 7159 output. 但是,Python的json.dumps()会产生有效的RFC 7159输出。

If your application requires JSONlint compliance, then by all means add a list or dictionary: 如果您的应用程序要求符合JSONlint,则一定要添加一个列表或字典:

>>> print json.dumps([data])
["[for: css=a[title=\"See LLCAutoSept files\"]]"]
>>> print json.dumps({'data': data})
{"data": "[for: css=a[title=\"See LLCAutoSept files\"]]"}

JSONlint.com validates either of these as valid. JSONlint.com会验证这两个都是有效的。

There was, for a time, quite some confusion over this, with RFC 4627, ECMA-262 and ECMA-404 and actual implementations disagreeing over what was allowed; 一段时间以来,RFC 4627,ECMA-262和ECMA-404引起了很大的混乱,实际的实现方式在允许的范围上存在分歧。 at least RFC 7159 agrees with ECMA-404 now on this. 至少RFC 7159现在就此同意ECMA-404。 Also see What is the minimum valid JSON? 另请参阅什么是最低有效JSON?

这是无效的json,因为它没有数组的键,也没有用于打开和关闭大括号或方括号的键,因此您无法在jsonlint.com上对其进行验证

This works for me 这对我有用

data = {'string':'[for: css=a[title="See LLCAutoSept files"]]'}
print(json.dumps(data))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM