I have the following string:
var str = 'jfkdjffddf{aaa:12,bbb:25}kfdjf';
And I want to fetch the object from it:
var objStr = str.match('/{(.*?)}/')[1]; // aaa:12,bbb:25
Now I want to use this fetched string as an object:
var obj = JSON.parse('{' + objStr + '}');
Do some operations on it, convert to string back again and replace in the initial text.
The problem is I get unexpected token a on 1 line in my script, the problem is thus probably JSON.parse.
What's the problem, and how can I solve this?
Related
I'm attempting to parse the following JSON string (not in control of the format, I know it's hideous).
var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';
obj = JSON.parse(json);
I'm getting Error: Unexpected token w in JSON at position 43 which is where the first value of nestedjsonstr begins. Is there any elegant way to parse this?
Maybe this can help you out. You replace the curly braces inside your string without the ", and remove the \.
var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';
json = json.replace('\"{', '{').replace('}\"', '}').replace('\\"', '"');
obj = JSON.parse(json);
console.log(obj);
The case:
var s = '{"a": 2}';
var d = JSON.parse(s); // d = Object {a: 2}
It is OK.
The similar case does not parse string, however. Why?
var s = "{'a': 2}";
var d= JSON.parse(s) // Uncaught SyntaxError: Unexpected token ' in JSON at position 1
Expected result - parsed object like in the first case. It should have worked because ' and " are interchangeable in javascript.
According to the standard, you need double quotes to denotes a string, which a key is.
It should have worked because ' and " are interchangeable in javascript.
JSON is not JavaScript.
JSON strings must be delimited with quotation marks, not apostrophes.
See the specification:
A string begins and ends with quotation marks.
this is my string,
var str=""{\"checkedRows\":\"[{\"SlNo\":\"1\",\"ItemCode\":\"8\",\"ItemDetail\":\"Cassue Nut\",\"Qty\":\"140\",\"Rate\":\"2000\",\"Amount\":280000\"}]\",\"checkedIndex\":\"[0]\"}"";
I'm trying to get substring as below
[{\"SlNo\":\"1\",\"ItemCode\":\"8\",\"ItemDetail\":\"Cassue Nut\",\"Qty\":\"140\",\"Rate\":\"2000\",\"Amount\":280000\"}]
And i'm trying below code to split
var newStr = str.substring(str.lastIndexOf("[") + 1, str.lastIndexOf("]"))
but unable to fetch it.
Firstly note that you have an extra leading and trailing double quote around your JSON string. Secondly the JSON itself is completely malformed. You need to fix the errors it has (extra/mis-matched double quotes mostly) so it looks like this:
'{"checkedRows":[{"SlNo":"1","ItemCode":"8","ItemDetail":"Cassue Nut","Qty":"140","Rate":"2000","Amount":280000}],"checkedIndex":[0]}'
Once you've done that you can parse the string to an object, then retrieve the checkedRows property and stringify that again, like this:
var str = '{"checkedRows":[{"SlNo":"1","ItemCode":"8","ItemDetail":"Cassue Nut","Qty":"140","Rate":"2000","Amount":280000}],"checkedIndex":[0]}';
var obj = JSON.parse(str);
var newStr = JSON.stringify(obj.checkedRows);
console.log(newStr);
In my application when I enter value as my"name in text field the framework makes a String like (this i can not control):
"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"
Now this String is passed to JSON.parse() method which produces an error because of ambiguous name field as
\"name\":\"my\"name\"
var str = JSON.parse("[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]")
This results in JSON exception
Is there anything I can do with the string:
"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"
To escape double quote character in my " name as my \" name to make it valid for JSON.parse method.
I can not control JSON String, I am just passing name as my"name and framework creates a String which is passed to JSON.parse()
I went through a series of text replace. You can try this:
var str = "[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]";
JSON.parse(
str.replace(/\\/i,"").
replace(/{"/g,"{'").
replace(/":"/g,"':'").
replace(/","/g,"','").
replace(/"}/g,"'}").
replace(/'/g,"\###").
replace(/"/g,"\\\"").
replace(/###/g,"\"")
);
It will give back your desired JSON array
var str = "[{\"id\":\"201500000001002\"}]";
str.replace("\"*","\\\"");
var obj = JSON.parse(str);
I've been looking for an answer to this, but whatever method I use it just doesn't seem to cut off the new line character at the end of my string.
Here is my code, I've attempted to use str.replace() to get rid of the new line characters as it seems to be the standard answer for this problem:
process.stdin.on("data", function(data) {
var str;
str = data.toString();
str.replace(/\r?\n|\r/g, " ");
return console.log("user typed: " + str + str + str);
});
I've repeated the str object three times in console output to test it. Here is my result:
hi
user typed: hi
hi
hi
As you can see, there are still new line characters being read between each str. I've tried a few other parameters in str.replace() but nothing seems to work in getting rid of the new line characters.
You are calling string.replace without assigning the output anywhere. The function does not modify the original string - it creates a new one - but you are not storing the returned value.
Try this:
...
str = str.replace(/\r?\n|\r/g, " ");
...
However, if you actually want to remove all whitespace from around the input (not just newline characters at the end), you should use trim:
...
str = str.trim();
...
It will likely be more efficient since it is already implemented in the Node.js binary.
You were trying to console output the value of str without updating it.
You should have done this
str = str.replace(/\r?\n|\r/g, " ");
before console output.
you need to convert the data into JSON format.
JSON.parse(data) you will remove all new line character and leave the data in JSON format.