-1

Hi I have a string that looks like this,

ll: 11, kw: sw, wit: jajar

This data is coming from a Google spreadsheet so this is the way they represent rows.

I want this to be converted to JavaScript for easy parsing. I tried the following but apparently didn't work.

var mz = data.feed.entry[0].content.$t; //which is ll: 11, kw: sw, wit: jajar
var text = "{"+ miz +"}"
var json = JSON.parse(text)

However this doesn't convert it to JSON and gives me the following error,

SyntaxError: JSON.parse: unterminated string at line 1 column 35 of the JSON data

How can I convert such a string to JSON for easy parsing? I also tried splitting the ext using ',' but that give false data if the column contained an ',' in the data so splitting is also not a good solution.

Thanks

rksh
  • 3,920
  • 10
  • 49
  • 68
  • To make it a valid json, you have to replace whitespaces with quotes (given there are only single whitespaces). Commas should also be replaced: , -> ", – Alexander Davydov Jul 05 '16 at 10:55
  • This string isn't in JSON format. You need at least braces. Check it out using JSONlint.com. – Sablefoste Jul 05 '16 at 10:56
  • 1
    Can it be like `wit: Hello foo, ...`? – Rajesh Jul 05 '16 at 11:02
  • Will it contain things other than alphanumeric characters? – gcampbell Jul 05 '16 at 11:04
  • @gcampbell at the moment it doesn't have anything other than alpha numeric characters but might include emojies in future – rksh Jul 05 '16 at 11:08
  • Can it be something like : `{"ll": "11", "kw": "sw, wit: jajar"}` ? – Himanshu Tyagi Jul 05 '16 at 11:12
  • I guess, since it is coming from google spreadsheet, we should assume, it can be in any format. I'd recommend to check if there are specific formats in which you can read rather than parsing string. – Rajesh Jul 05 '16 at 11:15
  • This might help [Access Google Spreadsheet or Google Data API only with Javascript](http://stackoverflow.com/questions/4143901/access-google-spreadsheet-or-google-data-api-only-with-javascript) – Rajesh Jul 05 '16 at 11:23

5 Answers5

1
   var mz = "ll: 11, kw: sw, wit: jajar";   
    var str = mz.replace(/:/g, '":"');
    str = str.replace(/,/g, '","');
    str = '"' + str + '"';
    var str = '"ll":"11","kw":"sw" ,"wit":"jajar"';
    var text = '{"contents":[' + '{' + str + '}]}';
    obj = JSON.parse(text);
    alert(obj.contents[0].ll + " " + obj.contents[0].kw + " " + obj.contents[0].wit);

This works fine. try this.

0

You have to make it proper json.

var str = '11: 11, kw: sw, wit: jajar';
str = '{"' +str.replace(/ /gm,"").replace(/:/gm, '":"').replace(/,/gm,'","') + '"}';
console.log(str);

var obj = JSON.parse(str);

console.log(JSON.stringify(obj));
Shubham
  • 1,755
  • 3
  • 17
  • 33
0

You could force the format into JSON (since it is similar), or you could just parse it yourself:

var obj = "ll: 11, kw: sw, wit: jajar".split(", ")
    .reduce(function(prev, curr) {
        var keyValue = curr.split(": ");
        var key = keyValue[0];
        var value = keyValue[1];
        var num = Number.parseFloat(value);
        if (value === "true" || value === "false") {
            return (prev[key] = value === "true", prev);
        } else if (!Number.isNaN(num)) {
            return (prev[key] = num, prev);
        }
        return (prev[key] = value, prev);
    }, {});
console.log(obj);

This should preserve Boolean & Number primitives as well as assuming everything else is a string.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • Again you're splitting it by the commas, if you split the string by the commas it will give false data as if the column contained a comma in its data. – rksh Jul 05 '16 at 11:17
  • 1
    @rksh indeed the same could be said of a colon. But it's hard to develop around that without a requirement of escape sequences from the OP – CodingIntrigue Jul 05 '16 at 11:20
0

All string parameters in json string should be quoted.
Use the following approach with String.replace and IsNaN(to preserve integer values) functions:

var mz = "ll: 11, kw: sw, wit: jajar",
    text = "{" + mz.replace(/(\w+?):\s?([^,]+)(,?)/g, function (m, p1, p2, p3) {
            var val = Number(p2);  // check for integer value
            return '"' + p1 + '":' + (isNaN(val)? '"'+p2+'"' : val) + p3;
        }) + "}";

console.log(JSON.parse(text)); // `Object {ll: 11, kw: "sw", wit: "jajar"}`
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • This would fail if data has comma. Sample: `"ll: 11, kw: sw, wit: jajar, abs"` – Rajesh Jul 05 '16 at 11:22
  • @Rajesh, if so, it would be a complex and contradictory case. Because, such comma can be in the middle like `"ll: 11, kw: sw, jajar, wit: 222"`. In such case, how could we know if it was `"kw": "sw, jajar", ...,` or it was meant as `...,"jajar, wit": 222`(property name with comma) ?! – RomanPerekhrest Jul 05 '16 at 11:31
  • Issue is OP is reading from google spreadsheet, so user can enter any data. Parsing string would be a painful and will have lots of loopholes. Ideal way would be to check if google spreadsheet provides data in any specific format that we can consume and safely parse. Your solution is great but I guess OP is looking in wrong direction. – Rajesh Jul 05 '16 at 11:41
  • @Rajesh, I also think that there should be a way to get data from google spreadsheet in a more convenient and predictable format – RomanPerekhrest Jul 05 '16 at 11:48
  • @RomanPerekhrest google spreadsheets can output data in 2 ways either json or xml I selected the json method because it is the easier to parse however the way google spreadsheet provides data in a given row is like that – rksh Jul 05 '16 at 14:46
-1

you may do like this:

var xx="ll: 11, kw: sw, wit: jajar";

xx=xx.split(",");
var t={};
xx.forEach(function(x){
x=x.split(":");
t[x[0].trim()]=x[1].trim();
});

console.log(t);
Deepak Sharma
  • 1,117
  • 1
  • 12
  • 22
  • x[0] and x[1] are the values splited from string. one will become key and one data – Deepak Sharma Jul 05 '16 at 11:04
  • like i said the split can give an error, if you split it according to commas and if the column contained a comma then it gives false data. I have mentioned that in the question. – rksh Jul 05 '16 at 11:10
  • @rksh column can also have `:` in them. Right? If yes, you can even split based on commas. And even `JSON.parse` might give issues in it – Rajesh Jul 05 '16 at 11:13
  • comma yaar.. its a community. if you specify a string ,answer would get according to that string. there can be N number of , and :. how it will convert to a json. you must have a format fixed. y -1 rating.?? – Deepak Sharma Jul 05 '16 at 11:16