How to make string to json object - javascript

I have below string
'[{\'Question\': \'a Names and Roles (if known)\'}]'
I need to convert it into JSON.
I tried JSON.parse(s)
I got error SyntaxError: Unexpected token ' in JSON at position 2
and also
> eval(s)
SyntaxError: Unexpected string
Any help would be really appreciable

Problem is that you need to pass string inside JSON.parse(s).
Please make sure s is a string

'[{*Question\': at the point of asterisk you need a \' don't you?
So it should be
'[{\'Question\': \'a Names and Roles..
EDIT
Found this after a bit of research. Problem is with the single quote. Replace them with double quotes, you are good to go. See this fiddle, to check this out in action.
Additionally, I had to modify "[\'NA\']" in your string, to get it to working. That is also invalid JSON. If it is an array that you want it to be, you should put it like [\"NA\"].

Related

Adding variables in string JS

I am using a string to store some HTML. However, the string needs to have some variables. The method I am using to input this variables is encountering a problem. There are quotes in my HTML. Therefore the string is cutting short where I don't want it to.
base="<h2>"+data[i]+"</h2><br><button onclick='vote('"+data[i]+'"); return false'>Vote for ME!</button>"
However, I am getting this error.
'vote(' Uncaught SyntaxError: Unexpected end of input
Even if I remove the 2 single quotes in the brackets, I am getting an error.
'vote(Iron Man); return false': Uncaught SyntaxError: missing ) after argument list. NOTE: Iron Man is the value of data[i].
Thanks in advance!
You've got a ' and a " flipped around.
base="<h2>"+data[i]+"</h2><br><button onclick='vote('"+data[i]+'"); return false'>Vote for ME!</button>"
^^---- flip these two
Template literals can make complicated string concatenations much more readable and less error-prone as it would eliminate the need for most of the " double quotes in your code sample:
base = `<h2>${data[i]}</h2><br><button onclick="vote('${data[i]}'); return false">Vote for ME!</button>`

JSON.parse get "Uncaught SyntaxError: Unexpected token h"

I get the syntax error when I try to pass the following string:
JSON.parse("[{\"Date\": \"4/4/2016 4:15:19 PM\", \"Message\":\"<h3>New
Message</h3> Generated at 4/4/2016 4:15:19 PM.<br/><br/>Heavy Responsive
URL: <a href=\"https://performingarts.withgoogle.com/en_us\" ></a><br/><br/>
<img src=\"https://s-media-cache-ak0.pinimg.com/236x/06/bd/ac/06bdacc904c12abdce3381ba1404fd7e.jpg\" /> \"} ]");
I know that the error come from the link when I use double quote.
If I use single quote then no issue, but the data is getting from server side, I got no control over what going to pass in so I can only control on my side.
From what I read from the internet so far, I tried the following:
Use JSON.stringify first, then only use JSON.parse. I can parse
with no issue but problem occur when I try to loop the data. Instead
of looping it as JSON, the loop take the data as string and loop
every single text.
Escape every double quote which I'm currently doing, but it's not
working as shown above. But if I replace every double quote to
literal, I'm afraid some of the message that suppose to be double
quote will turn into literal as well, which will result in weird
looking message.
Please advice what other alternative I have to solve this.
You have JSON embedded in a JavaScript string literal.
" and \ are special characters in JSON and are also special characters in a JavaScript string literal.
href=\"https: escapes the " in the JavaScript string literal. It then becomes a " in the JSON. That causes an error.
When you want the " as data in the JSON you must:
Escape the " for JavaScript (as you are doing already)
Escape the " for JSON by adding a \.
Escape the \ for JavaScript
href=\\\"https:

JS - JSON.parse - preserve special characters

I'm running a NodeJS app that gets certain posts from an API.
When trying to JSON.parse with special characters in, the JSON.parse would fail.
Special characters can be just any other language, emojis etc.
Parsing works fine when posts don't have special characters.
I need to preserve all of the text, I can't just ignore those characters since I need to handle every possible language.
I'm getting the following error:
"Unexpected token �"
Example of a text i'm supposed to be able to handle:
"summary": "★リプライは殆ど見てません★ Tokyo-based E-J translator. ここは流れてくるニュースの自分用記録でRT&メモと他人の言葉の引用、ブログのフィード。ここで意見を述べることはしません。「交流」もしません。関心領域は匦"�アイルランドと英国(他は専門外)※Togetterコメ欄と陰謀論が嫌いです。"
How can I properly parse such a text?
Thanks
You have misdiagnosed your problem, it has nothing to do with that character.
Your code contains an unescaped " immediately before the special character you think is causing the problem. The early " is prematurely terminating the string.
If you insert a backslash to escape the ", your string can be parsed as JSON just fine:
x = '{"summary": "★リプライは殆ど見てません★ Tokyo-based E-J translator. ここは流れてくるニュースの自分用記録でRT&メモと他人の言葉の引用、ブログのフィード。ここで意見を述べることはしません。「交流」もしません。関心領域は匦\\"�アイルランドと英国(他は専門外)※Togetterコメ欄と陰謀論が嫌いです。"}';
console.log(JSON.parse(x));
You need to pass a string not as an object.
Example
JSON.parse('{"summary" : "a"}');
In your case it should be like this
JSON.parse(
'{"summary" : "★リプライは殆ど見てません★ Tokyo-based E-J translator. ここは流れてくるニュースの自分用記録でRT&メモと他人の言葉の引用、ブログのフィード。ここで意見を述べることはしません。「交流」もしません。関心領域は匦�アイルランドと英国(他は専門外)※Togetterコメ欄と陰謀論が嫌いです。"}')

Issue in accessing JSON object?

Am facing issue in accessing the JSON object :
JSON Object am receiving is :
{"71":"Heart XXX","76":"No Heart YYYY"}
I tried to get the value of 71 and 72 separately and use it ...
but am getting some compile time issue as :
Syntax error on token ".71", delete this token
Code:
var map=$("#jsonText").val();
alert(map);
var obj=jQuery.parseJSON(map);
alert("JSON ::"+obj.71);
If am printing obj , am able to view [Object Object]
Can any one out there please help me to find the mistake i did ..I know the question above is asked in many threads in SO . Below are the few threads i found , but failed when i attempted to implement it ..
jquery json parsing
Also tried using the Jquery tutorial given in
Jquery JSON
Its working fine if the key is a String but getting the above error if its a number ...
Try this:
alert("JSON ::" + obj[71]);
"71" isn't a valid property identifier: an identifier should start with a letter, the underscore or the dollar sign. You can avoid this problem using square brackets instead.
Note: everything that's put between square brackets is converted into strings. Even functions, DOM elements or regular expressions: they're all converted with their toString methods, or their superclass' toString.
So 71 there is converted into "71". If you want a little more performance you can directly use the latter. If you don't need it, you can cut some key presses with just 71.
Use instead
alert("JSON ::"+obj["71"]);
according to the rules or javascript a identifier should not start by a number so if it starts by a number or for that matter contains spaces and other special charcters then you should access it by using the [] operator and not by . operator
so obj.71 is invalid but obj["71"] is
try using this site:
http://json.parser.online.fr/

Whats wrong with this JSON syntax?

Am trying this on my chrome debugger console, and am getting a SyntaxError;
JSON.parse("[{"name":"gath","age":10}]");
>SyntaxError
What is the correct way of parsing the JSON string?
Please note this question is a follow up to my earlier one, which am yet to get an answer!
You need to escape your double-quotes.
JSON.parse("[{\"name\":\"gath\",\"age\":10}]");
or, for better readabilty, define the string with single quotes:
JSON.parse('[{"name":"gath","age":10}]');
JSON.parse("[{\"name\":\"gath\",\"age\":10}]");
You cant have double quotes inside double quotes
You need to escape the "
or do JSON.parse('[{"name":"gath","age":10}]');
Enclose it in single quotes and it will parse correctly.
JSON.parse('[{"name":"gath","age":10}]');
Object
age: 10
name: "gath"
__proto__: Object
Replace
JSON.parse("[{"name":"gath","age":10}]");
With
JSON.parse('[{"name":"gath","age":10}]');

Categories

Resources