【问题标题】:How to parse a json in python which was created with json stringfy using javascript如何在 python 中解析使用 javascript 的 json stringify 创建的 json
【发布时间】:2020-08-11 14:40:06
【问题描述】:

我有一个在 JavaScript 中字符串化的对象,我想在 python 中解析它。但是我收到以下错误:

Traceback(最近一次调用最后一次):文件“main.py”,第 7 行,在 y = json.loads(x) 文件“/usr/lib/python3.8/json/init.py”,第 357 行,加载中 在解码中返回 _default_decoder.decode(s) 文件“/usr/lib/python3.8/json/decoder.py”,第 337 行 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 文件“/usr/lib/python3.8/json/decoder.py”,第 353 行,在 raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 18 (char 17)

javascript

const text = 'K said "Hello World" ';

const obj = {
  text: text
}

const stringified = JSON.stringify(obj);

字符串化的输出是:{"text":"K said \"Hello World\" "}

蟒蛇

import json

x = '{"text":"K said \"Hello World\" "}'

y = json.loads(x)

print(y)

【问题讨论】:

    标签: javascript python json


    【解决方案1】:

    你需要一个 raw 字符串来 jsonify 这个字符串在 python 中没有被正确解析。在字符串之前放一个 r 应该可以完成工作

    import json
    
    x = r'{"text":"K said \"Hello World\" "}'
    
    y = json.loads(x)
    
    print(y)
    >>> {'text': 'K said "Hello World" '}
    

    【讨论】:

      【解决方案2】:

      试试这个:

      变量x 必须是

      x = "{\"text\":\"K said \"Hello World\" \"}"
      y = json.loads(x)
      
      print(y)
      >>> {'text': 'K said "Hello World" '}
      
      

      【讨论】:

        猜你喜欢
        • 2015-03-10
        • 2014-07-22
        • 1970-01-01
        • 2015-05-11
        • 2021-08-21
        • 2012-09-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-30
        相关资源
        最近更新 更多