【问题标题】:How to remove some unnecessary spaces in json file?如何删除json文件中一些不必要的空格?
【发布时间】:2016-05-15 07:32:01
【问题描述】:

我是这个 json 和 node.js 的新手。现在我有 json 文件,其中有一些不必要的空格。怎么去掉?

.json 文件

{
"Product_Name": "Logitech M235 Wireless Mouse (Red)",
"Brand": "Logitech",
"Color": "\n            \n                Red\n            \n        ",
"Image": "http://ecx.images-amazon.com/images/I/31UXrp3AcLL._SY300_QL70_.jpg",
"Price": "   699.00",
"Rating": "4.4 out of 5 stars"
}

颜色值包含一些空格,我不希望这些空格我只需要“红色”。

我正在写 json 文件

server.js

var json = {Product_Name : "", Brand : "", Color : "", Image : "", Price : "", Rating : ""};
            
        var P_name = $('#title').children().text();
        var brand = $('#brand').text();
        var color = $('.a-row').find('span.selection').text();
        var price = $('#price').find('span.a-size-medium').text();
        var rating = $('#averageCustomerReviews').find('span.a-icon-alt').text();
        var image = $('.imgTagWrapper').children().attr('src');
            
        json.Product_Name = P_name;
        json.Brand = brand;
        json.Color = color;
        json.Price = price;
        json.Rating = rating;
        json.Image = image;
            
        fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err){
            console.log('File successfully written! - Check your project directory for the output.json file');
        })

【问题讨论】:

    标签: jquery json node.js


    【解决方案1】:

    只需像这样在颜色变量中替换字符串中的空格和换行符

    color.trim()
    

    【讨论】:

    • 修剪在nodejs中被调用所以是有效的
    • 不用担心容易出错
    • 谢谢@simon-p-r。我用你的回答解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 2014-03-28
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 2014-07-14
    • 2014-07-25
    • 1970-01-01
    相关资源
    最近更新 更多