【问题标题】:JavaScript Object to JSON using python使用 python 将 JavaScript 对象转换为 JSON
【发布时间】:2014-08-05 08:48:26
【问题描述】:

我正在尝试从网站检索最初看起来像普通 JSON 的内容。但它是一个不是有效 JSON 的 JavaScript 对象。 有没有办法使用python将此字符串转换为JSON?

例如:

{
 firstName:"John",
 lastName:"Doe",
 age:50,
 eyeColor:"blue",
 dimensions:[
     {
      height: "2",
      width: "1"
     }
]
}

【问题讨论】:

    标签: python json javascript-objects


    【解决方案1】:

    使用可以处理此类输入的非严格模式的解析器。我一直在推荐 demjson 这样的东西,因为它是我搜索 python non-strict json parser 时出现的第一个可行的候选人。

    >>> demjson.decode("""{
    ...  firstName:"John",
    ...  lastName:"Doe",
    ...  age:50,
    ...  eyeColor:"blue",
    ...  dimensions:[
    ...      {
    ...       height: "2",
    ...       width: "1"
    ...      }
    ... ]
    ... }""")
    {u'eyeColor': u'blue', u'lastName': u'Doe', u'age': 50, u'dimensions': [{u'width
    ': u'1', u'height': u'2'}], u'firstName': u'John'}
    

    【讨论】:

      【解决方案2】:

      恐怕 Python 不懂 JavaScript。如果可以使用Node.js,则很容易将输入转换为JSON。

      编辑:当然您也可以使用每个浏览器的 JavaScript 控制台来执行此操作。

      > d = {
      ...  firstName:"John",
      ...  lastName:"Doe",
      ...  age:50,
      ...  eyeColor:"blue",
      ...  dimensions:[
      ...      {
      .....       height: "2",
      .....       width: "1"
      .....      }
      ... ]
      ... };
      { firstName: 'John',
        lastName: 'Doe',
        age: 50,
        eyeColor: 'blue',
        dimensions: [ { height: '2', width: '1' } ] }
      > JSON.stringify(d)
      '{"firstName":"John","lastName":"Doe","age":50,"eyeColor":"blue","dimensions":[{"height":"2","width":"1"}]}'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-07
        • 1970-01-01
        • 1970-01-01
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-02
        相关资源
        最近更新 更多