【问题标题】:write into a js file without passing in string quotes (in Python)在不传入字符串引号的情况下写入 js 文件(在 Python 中)
【发布时间】:2018-09-26 16:09:22
【问题描述】:

我正在编写一个解析器来从 GitHub api 抓取数据,我想将文件输出为以下 .js 格式:

//Ideal output
var LIST_DATA = [
{
    "name": "Python",
    "type": "category"
}]

虽然我在使用变量var LIST_DATA 写入output.js 文件时遇到问题,但无论我对字符串做什么,最终结果都会显示为"var LIST_DATA"

例如:

//Current Output
"var LIST_DATA = "[
{
    "name": "Python",
    "type": "category"
}]

我的 Python 脚本:

var = "var LIST_DATA = "
with open('list_data.js', 'w') as outfile:
     outfile.write(json.dumps(var, sort_keys = True))

我也根据this StackOverflow 的答案尝试使用strip 方法并得到相同的结果

var = "var LIST_DATA = "
with open('list_data.js', 'w') as outfile:
     outfile.write(json.dumps(var.strip('"'), sort_keys = True))

我假设,每当我将文本转储到 js 文件中时,字符串都会与双引号一起传入...有没有办法解决这个问题?

谢谢。

【问题讨论】:

  • 在编写var LIST_DATA = 时不要使用json.dumps,它会被解释为JSON 值,因此会被引号括起来。
  • var LIST_DATA = [... 不是有效的 JSON,所以json.dumps 永远不会输出它。你需要的是outfile.write('var LIST_DATA = '); json.dump(whatever_proper_data, outfile, indent=1)
  • 非常感谢大家,哇...当然,现在说得通了:json = quote...。

标签: python json string


【解决方案1】:

试试

var = '''var LIST_DATA = [
{
    name: "Python",
    type: "category"
}]'''
with open("list_data.js", "w") as f:
    f.write(var)

json 库不是您在此处寻找的。​​p>

此外,Javascript 中的字典不需要带引号的键,除非键中有空格。

输出:

【讨论】:

    【解决方案2】:

    如果您将字符串传递给json.dumps,它将始终被引用。第一部分(变量的名称)不是 JSON - 所以您只想逐字编写,然后使用 json.dumps 编写对象:

    var = "var LIST_DATA = "
    my_dict = [
      {
        "name": "Python",
        "type": "category"
      }
    ]
    with open('list_data.js', 'w') as outfile:
        outfile.write(var)
        # Write the JSON value here
        outfile.write(json.dumps(my_dict))
    

    【讨论】:

      猜你喜欢
      • 2014-01-02
      • 1970-01-01
      • 2021-11-25
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2011-01-30
      • 1970-01-01
      相关资源
      最近更新 更多