最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I safely use JSON.parse on a string object that might be a simple string or a string object? - Stack Overfl

programmeradmin6浏览0评论

I need to be able to parse a string in an object format or in a plain string format. what is the safest way to do this?

I tried JSON.parse(data) but it does not work in case that data is a plain string.


EDIT - The chosen solution

Thanks to you, this is how I solved the problem:

try {
    dataObj = JSON.parse(data);
} catch (err) {
    if (typeof data === "object") {
        dataObj = data;
    } else {
        dataObj = {};
    }
}

I need to be able to parse a string in an object format or in a plain string format. what is the safest way to do this?

I tried JSON.parse(data) but it does not work in case that data is a plain string.


EDIT - The chosen solution

Thanks to you, this is how I solved the problem:

try {
    dataObj = JSON.parse(data);
} catch (err) {
    if (typeof data === "object") {
        dataObj = data;
    } else {
        dataObj = {};
    }
}
Share Improve this question edited Jul 20, 2015 at 17:12 Robert Koritnik 105k56 gold badges286 silver badges413 bronze badges asked Jul 19, 2015 at 13:16 RavitRavit 1,5423 gold badges19 silver badges25 bronze badges 2
  • If data can be an object, why don't you test that before you are trying to parse it? That would make more sense. Also, if it can be an object, why don't you mention that in your question? You said the value would be a string. – Felix Kling Commented Jul 19, 2015 at 22:40
  • After I wrote the question I found more edge cases. – Ravit Commented Jul 20, 2015 at 7:02
Add a ment  | 

3 Answers 3

Reset to default 3

Create yourself a helper function and use that.

function parseValue(value) {
    try
    {
        return JSON.parse(value);
    }
    catch (ex)
    {
        // JSON format was invalid
        // handle errors is you need to
    }

    return value;
}

If you're brave enough you can also extend String.prototype so calling it would bee really straight forward.

String.prototype.parseJSON = String.prototype.parseJSON || function() {
    try
    {
        return JSON.parse(this);
    }
    catch (ex)
    {
        // JSON format was invalid
        // handle errors is you need to
    }

    return this;
};

And then you'd simply call it this way:

// string in a variable
var s = "Some non-JSON string";
s.parseJSON();
// string literal
'{"b":true,"n":1}'.parseJSON();

Use try catch:

var result;
try {
   result = JSON.parse(data);
} catch (err) {
   if (typeof data == 'string') result = data;
   else console.error(err);
}

Assuming the JSON will always have the same format, you could also check whether the string starts with a {" (or just {), and only then parse it with JSON.parse.

It really depends of the possible input though.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论