【问题标题】:JSON string stored in SqlLite -- how to escape single and double quotesSqlite中存储的JSON字符串——如何转义单引号和双引号
【发布时间】:2014-08-19 18:55:41
【问题描述】:

我需要在 sqlite 中存储以下 json 消息。但是我无法做到这一点,因为我的输入消息中有单引号。虽然处理了双引号的转义,但是单引号还是会报错。如何解决?输入信息如下..

'{
"request" : [
    {
        "name" : "test",
        "number" : "8",
        "data" : {
            "message" : "This is a test 'messa'ge "
        }
    }
],

"data1" : {
    "data2" : 1,
    "data3" : "Hello"
},

"message1" : "tes't example"
}'

【问题讨论】:

  • CL 不应该关闭它,“dup”与使用 SQLite 无关。
  • @muistooshort 问题中实际显示的唯一问题是 Ruby 引用。

标签: ruby json sqlite escaping


【解决方案1】:

你的字符串会导致 ruby​​ 语法错误:

syntax error, unexpected tIDENTIFIER, expecting end-of-input
            "message" : "This is a test 'messa'ge "

要创建你的字符串,你可以使用:

  1. %q[ ],相当于单引号。

  2. %Q[ ],相当于双引号。

您可以使用任何字符作为分隔符,例如。

%q|Dave's head is small.|

%q{Dave's head is small.}

%q=Dave's head is small.=

这样您就可以无错误地创建字符串,如下所示:

your_string =  %q[{
    "request" : [
        {
            "name" : "test",
            "number" : "8",
            "data" : {
                "message" : "This is a test 'messa'ge "
            }
        }
    ],

    "data1" : {
        "data2" : 1,
        "data3" : "Hello"
    },

    "message1" : "tes't example"
    }]

【讨论】:

    【解决方案2】:
    ins = db.prepare('insert into table_name (column_name) values (?)')
    ins.execute(your_string)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多