【问题标题】:Remove quotes from a json object value从 json 对象值中删除引号
【发布时间】:2016-06-28 17:05:25
【问题描述】:

我在节点 js 中使用 Woocommerce API 将产品数据从 mssql server db 导入我的 woocommerce 数据库。

我正在通过 ms sql 查询的记录集包含 images field

在 Woocommerce API 中,要导入图像,我需要这种类型的 json object

var data = {
  product: {
    title: 'Premium Quality',
    type: 'simple',
    regular_price: '21.99',
    description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.',
    short_description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.',
    categories: [
      9,
      14
    ],
    **images: [
      {
        src: 'http://example.com/wp-content/uploads/2015/01/premium-quality-front.jpg',
        position: 0
      },**
      {
        src: 'http://example.com/wp-content/uploads/2015/01/premium-quality-back.jpg',
        position: 1
      }
    ]
  }
};

休息很好,但我对图像有问题,因为我在引号images: '[{...}]' 中获取图像 json,因为数据类型是 db 表中的 varchar。

由于这个引号,图像不会通过 Woocommerce rest API 插入到数据库中。

我想专门从图片中删除引号。或任何其他建议。

我是节点 js 的新手。有没有人可以帮忙。

【问题讨论】:

  • “varchar”类型虽然接受字符串。你确定这是问题所在?

标签: json node.js wordpress woocommerce woocommerce-rest-api


【解决方案1】:

据我了解,您的问题是您在指定图像位置的字符串的开头和结尾处获得了额外的""。 您只需在 js 中删除字符串变量的第一个和最后一个字符。

解决方案:

var x = String(/'[{...}]'/);
str = x.substring(1, x.length - 1);
var image = str.substring(1, str.length - 1);

演示:

function myFunction() {
  var x = String(/'[{...}]'/);
  str = x.substring(1, x.length - 1);
  var res = str.substring(1, str.length - 1);
  document.getElementById("demo").innerHTML = res;
}
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

演示:

从字符串的开头和结尾删除“”:

var someStr = String('[{...}]');
alert(someStr)
alert(someStr.replace(/^"(.*)"$/, '$1'));

var someStr = String('"[{...}]"');
alert(someStr)
alert(someStr.replace(/^"(.*)"$/, '$1'));

var test = "\"House\"";
console.log(test);
console.log(test.replace(/\"/g, "")); 

参考:remove-double-quotes-from-json-return-dataCan you create a JavaScript string without using ' or " quotes?

【讨论】:

  • 我只需要从图像中替换它,我无法拆分数据变量。
  • function getConn() { var conn = new sql.Connection(dbConfig); var req = new sql.Request(conn); conn.connect(function (err) { if (err) { console.log(err); return; } req.execute("getProductWoo", function (err, recordset){ if (err) { console.log(err); } else { var data = JSON.parse(JSON.stringify({ products : recordset[0]})); WooCommerce.post('products/bulk', data, function(err, data, res) { console.log(res); }); } conn.close(); }); }); }
猜你喜欢
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 2014-09-06
  • 2015-10-08
  • 2014-06-16
  • 2017-08-08
相关资源
最近更新 更多