【问题标题】:How to properly convert a list of list into JSON in python?如何在python中正确地将列表列表转换为JSON?
【发布时间】:2020-09-23 13:33:32
【问题描述】:

我仍在使用 python 2.7。我有一个列表列表,其中有一些带双引号的字符串。以下是我所拥有的

new_row = [['<a href=/account_dtls/risks/edit/ACC-RISK-136053>ACC-RISK-136053</a>', 'Customer_152', 'External', 'Geographic / Diplomatic', u'Account', u'<span title=something "was" okay>something "was" okay</span>', 'gowri.subramanian', 'Open', 'saved', 'Client Location']]

我希望将其转换为 json。我在终端中的 python 解释器中按照以下步骤操作

<type 'list'>
>>> json.dumps(new_row)
'[["<a href=/account_dtls/risks/edit/ACC-RISK-136053>ACC-RISK-136053</a>", "Customer_152", "External", "Geographic / Diplomatic", "Account", "<span title=something \\"was\\" okay>something \\"was\\" okay</span>", "gowri.subramanian", "Open", "saved", "Client Location"]]'
>>>

这给了我一个带有双引号的整洁 json 字符串。但我的问题是我正在运行 DJANGO,并在其中将相同的列表列表转换为 json,并在我的日志文件中打印以下内容。

[["<a href=/account_dtls/risks/edit/ACC-RISK-136053>ACC-RISK-136053</a>", "Customer_152", "External", "Geographic / Diplomatic", "Account", "<span title=something \"was\" okay>something \"was\" okay</span>", "gowri.subramanian", "Open", "saved", "Client Location"]]

请注意,单词“was”周围的双引号没有用双反斜杠转义,而是用单反斜杠转义。我将它传递给前端并尝试使用 JSON.parse() 读取它,但它会抛出错误

Uncaught SyntaxError: Unexpected token '&'

当我检查时是这样的

[[&quot;&lt;a href=/account_dtls/risks/edit/ACC-RISK-136053&gt;ACC-RISK-136053&lt;/a&gt;&quot;, &quot;Customer_152&quot;, &quot;External&quot;, &quot;Geographic / Diplomatic&quot;, &quot;Account&quot;, &quot;&lt;span title=something \&quot;was\&quot; okay&gt;something \&quot;was\&quot; okay&lt;/span&gt;&quot;, &quot;gowri.subramanian&quot;, &quot;Open&quot;, &quot;saved&quot;, &quot;Client Location&quot;]]

所以我尝试用"替换&amp;quot

replace(/&amp;quot;/g,'"') 但现在我收到以下错误。 VM86:1 Uncaught SyntaxError: Unexpected token w in JSON at position 164

我在这里完全感到沮丧。有人可以帮我这里发生了什么吗?我该如何解决这个问题?

【问题讨论】:

标签: python json


【解决方案1】:

ast.literal_eval() 可能会像 here 所述帮助您。

【讨论】:

  • 我遵循了您的解决方案,但它现在给了我ValueError: malformed stringerror。
猜你喜欢
  • 1970-01-01
  • 2012-04-03
  • 2020-06-03
  • 2014-03-03
  • 2019-06-12
  • 2020-11-01
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多