简体   繁体   中英

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

How to convert this string into json in python?

>>> 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

You are looking at the Python string representation. It's valid Python code, containing valid 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.

However, Python's json.dumps() produces valid RFC 7159 output.

If your application requires JSONlint compliance, then by all means add a list or dictionary:

>>> 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.

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; at least RFC 7159 agrees with ECMA-404 now on this. Also see What is the minimum valid JSON?

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

This works for me

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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