Convert object string to JSON

2019-01-02 17:17发布

How can I convert a string that describes an object into a JSON string using JavaScript (or jQuery)?

e.g: Convert this (NOT a valid JSON string):

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"

into this:

str = '{ "hello": "world", "places": ["Africa", "America", "Asia", "Australia"] }'

I would love to avoid using eval() if possible.

19条回答
低头抚发
2楼-- · 2019-01-02 17:44

Your best and safest bet would be JSON5 – JSON for Humans. It is created specifically for that use case.

const result = JSON5.parse("{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }");

console.log(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/json5/0.5.1/json5.min.js"></script>

查看更多
听够珍惜
3楼-- · 2019-01-02 17:44

Maybe you have to try this:

str = jQuery.parseJSON(str)
查看更多
宁负流年不负卿
4楼-- · 2019-01-02 17:45

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }" var fStr = str .replace(/([A-z]*)(:)/g, '"$1":') .replace(/'/g, "\"")

console.log(JSON.parse(fStr))enter image description here

Sorry I am on my phone, here is a pic.

查看更多
只若初见
5楼-- · 2019-01-02 17:48

Just for the quirks of it, you can convert your string via babel-standalone

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";

function toJSON() {
  return {
    visitor: {
      Identifier(path) {
        path.node.name = '"' + path.node.name + '"'
      },
      StringLiteral(path) {
        delete path.node.extra
      }
    }
  }
}
Babel.registerPlugin('toJSON', toJSON);
var parsed = Babel.transform('(' + str + ')', {
  plugins: ['toJSON']
});
var json = parsed.code.slice(1, -2)
console.log(JSON.parse(json))
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

查看更多
路过你的时光
6楼-- · 2019-01-02 17:49

Your string is not valid JSON, so JSON.parse (or jQuery's $.parseJSON) won't work.

One way would be to use eval to "parse" the "invalid" JSON, and then stringify it to "convert" it to valid JSON.

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
str = JSON.stringify(eval('('+str+')'));

I suggest instead of trying to "fix" your invalid JSON, you start with valid JSON in the first place. How is str being generated, it should be fixed there, before it's generated, not after.

EDIT: You said (in the comments) this string is stored in a data attribute:

<div data-object="{hello:'world'}"></div>

I suggest you fix it here, so it can just be JSON.parsed. First, both they keys and values need to be quoted in double quotes. It should look like (single quoted attributes in HTML are valid):

<div data-object='{"hello":"world"}'></div>

Now, you can just use JSON.parse (or jQuery's $.parseJSON).

var str = '{"hello":"world"}';
var obj = JSON.parse(str);
查看更多
浮光初槿花落
7楼-- · 2019-01-02 17:51
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
var json = JSON.stringify(eval("(" + str + ")"));
查看更多
登录 后发表回答