javascript json parse with single quote - javascript

I am trying to transform into a json object the an object this works well with the following object and the associated code :
myStr = "{'key':'value'}"
JSON.parse(myStr.replace(/'/g, "\""));
The problem is that with the same code, I am getting an exception with the following object :
myStr = "{'key':'val'ue'}"
The error is unexpected token u. I would like to keep the single quote between l and u, and not replace it.
Is there anyway?

You could do this, but it feels a little hacky...
JSON.parse(myStr.replace(/{'/g, "{\"").replace(/'}/g, "\"}").replace(/':'/g, "\":\""));

Hope this may help you. Assuming the inner singe quote comes between alphabets.
myStr = "{'key':'val'ue'}"
JSON.parse(myStr.replace(/([a-z])'([a-z])/g, "$1\\'$2"));

Related

JSON parse double quotes

I encountered a very strange error. If I run JSON.Parse('[""d""]') then I have error: "Unexpected token d in JSON at position 3"
JSON.parse('["\"d\""]')
If I run console.log(JSON.stringify(['"d"'])) then I get '[""d""]'
console.log(JSON.stringify(['"d"']))
If I run console.log(JSON.parse(JSON.stringify(['"d"']))) then I get good result [""d""]
console.log(JSON.parse(JSON.stringify(['"d"'])))
If I use eval function then I have error: "Uncaught SyntaxError: Unexpected token d in JSON at position 3"
var someJson=JSON.stringify(['"d"']);
window.eval(`JSON.parse('${someJson}')`)
How fix it?
I use some external library and there is window.eval(JSON.parse('${JSON.stringify(t)}'))). Where t - json array with strings. String can contains double quoutes. It throws exception.
I found js changed my string value when I set it.
var someJson='["\"d\""]';
console.log(someJson);
It returns '[""d""]' and when I run JSON.Parse it is incorrect JSON.
How fix it?
JSON.parse('["\"d\""]')
\ is a special character in JS strings, so to include it in your JSON you need to escape it.
const yourString = '["\"d\""]';
const validJSON = '["\\"d\\""]'
const parsedData = JSON.parse(validJSON);
document.querySelector('#yourString').value = yourString;
document.querySelector('#validJSON').value = validJSON;
<p>Your string: <output id="yourString"></output>
<p>Valid JSON: <output id="validJSON"></output>
As a rule of thumb, embedding JSON in string literals is a waste of time and effort. You can just write the JS data structure you get from parsing the JSON.
#Quentin many thanks for idea! Result answer for me:
var someJson=JSON.stringify(['"d"']);
console.log(window.eval(`JSON.parse('${someJson.replaceAll('\\','\\\\')}')`))

I must replace some special characters on Code by Zapier

I need to replace some special characters on Zapier.
Since there are many substitutions, I want to do it through Code by Zapier.
I made the code, but I got the following error on Code by Zapier:
We had trouble sending your test through.
TypeError: str.replace is not a function
Here is the code:
str = inputData;
str.replace(/Á|Ä|À|Ã|Â/g, "A");
str.replace(/É|Ë|È|Ê/g, "E");
str.replace(/Í|Ï|Ì|Î/g, "I");
str.replace(/Ó|Ö|Ò|Õ|Ô/g, "O");
str.replace(/Ú|Ü|Ù|Û/g, "U");
output = [{outputData: str}];
I don't know why str.replace doesn't work on Code by Zapier. I tried use str = str.replace(), instead str.replace(), but it did not worked too.
Can someone help?
Looks like inputData is not a string but rather an object. So if you provided a field to the Code then you need to access it as a property of that object. Let's say the name of the variable is foo, then you need to access it as inputData.foo.replace() (see screenshot).

JSON to JavaScript, SyntaxError: Unexpected token &

I know this question has been asked numerous times, but I really don´t get it.
I am creating a site in MVC, and I'm creating a JSON string from my model. I then want to pass it as argument to a JavaScript function that uses it to plot a graph.
Here is were I create the JSON string. This indeed creates a valid JSON string, I checked it at JSONLint.
#{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var weightsAsJsonString = serializer.Serialize(Enumerable.Select(Model, weight =>
new
{
date = weight.Date,
value = weight.Value
}));
}
Further down I create a JavaScript variable from it and pass it into the JavaScript function:
var jsonStringToGraph = #weightsAsJsonString;
google.setOnLoadCallback(drawVisualization(jsonstring));
When I run this, the console prints 'SyntaxError: Unexpected token &' at the line were I declare jsonStringToGraph. I googled around and concluded that I should put ' ' around #weightsAsJsonString, so I do that.
Anyway, in my drawVisualization, I do this:
function drawVisualization(teststring) {
.......
var parsedJson = JSON.parse(teststring);
This gives me SyntaxError: Unexpected token & Index:1
I know that the code at the bottom is what is causing the exception, but I do not understand why. Do anyone understand what I am doing wrong?
Edit: This is the weightsAsJsonString
[{"date":"\/Date(1434492000000)\/","value":100.2},{"date":"\/Date(1434578400000)\/","value":99.2},{"date":"\/Date(1434664800000)\/","value":101.2},{"date":"\/Date(1434751200000)\/","value":98.2},{"date":"\/Date(1434837600000)\/","value":97.2},{"date":"\/Date(1434924000000)\/","value":96.2},{"date":"\/Date(1435010400000)\/","value":95.2},{"date":"\/Date(1435096800000)\/","value":94.2}]
It sounds like your issue is trying to inject content via Razor into JavaScript. By default # will HTML-encode your content, which doesn't work in the context of JavaScript.
#Html.Raw(weightsAsJsonString) will work better, and then your JS will have a JavaScript object, so there's no need for the JSON.parse later on.
When you do var jsonStringToGraph = #weightsAsJsonString; you are actually defining a JSON object and not a JSON string.
Hence when you do JSON.parse(teststring); you are trying to parse an object instead of a string.
Either put apostrophes around the first declaration var jsonStringToGraph = '#weightsAsJsonString'; or simply do not try to parse it again.

Converting a String into an Object

I'm receiving a string like obj{a="foo",b="bar",c=3,d=4.0} inside a nodejs environment I'm working in and I'm trying to convert this String into a reference-able Object like this:
{
a : "foo",
b : "bar",
c : 3,
d : 4.0
}
Assigned to obj of course.
I've used a myriad of formatting tricks but whenever I call JSON.parse() I get unexpected character errors. Usually on the first alpha-character it sees.
My next step is to write several nested loops to make all of the assignments manually but I'm hoping someone can point me in the right direction on how to parse this.
EDIT: Ok there's a little more to the story and I thought I should omit it but I guess explaining everything would be helpful.
The actual data packet that I'm receiving looks like this.
ack{a="000000061",b=0,c=2.0}\rb{a=244.0,b=255,c=4.0}\rc{a=6.0,b=55,c=55}endack;
So yeah that's the actual string I'm trying to parse into three distinct accessible Objects. I know I'm having a brain fart from a long day but yeah it's giving me a run for my money right now.
First replace the "=" with ":" and remove the obj infront
str = str.replace(/=/g, ":").replace("obj{", "{")
Since it's not in correct json format (but can be read by js parser) we can't use JSON.parse but we can use eval
eval("var obj = " + str);
Obvious there are some assumptions with this technique such that = always mean colon and you won't have obj{ as text (but the latter can be fixed with a simple substring method)
Keep in mind eval is also considered evil so use at your own risk. Imagine if the user were to send bad data, they could easily get into your parser and run something malicious. But hopefully this will give you an idea or inspiration to a better solution.
You can go a step further and use
str = 'obj{a="foo",b="bar",c=3,d=4.0}'
str = str.substr(3,str.length).replace(/([{,])([\w])=/g, '$1\"$2\":');
var obj = JSON.parse(str);

Parse ill formed JSON string

I am being sent an ill formed JSON string from a third party. I tried using JSON.parse(str) to parse it into a JavaScript object but it of course failed.
The reason being is that the keys are not strings:
{min: 100}
As opposed to valid JSON string (which parses just fine):
{"min": 100}
I need to accept the ill formed string for now. I imagine forgetting to properly quote keys is a common mistake. Is there a good way to change this to a valid JSON string so that I can parse it? For now I may have to parse character by character and try and form an object, which sounds awful.
Ideas?
You could just eval, but that would be bad security practice if you don't trust the source. Better solution would be to either modify the string manually to quote the keys or use a tool someone else has written that does this for you (check out https://github.com/daepark/JSOL written by daepark).
I did this just recently, using Uglifyjs to evaluate:
var jsp = require("uglify-js").parser;
var pro = require("uglify-js").uglify;
var orig_code = "var myobject = " + badJSONobject;
var ast = jsp.parse(orig_code); // parse code and get the initial AST
var final_code = pro.gen_code(ast); // regenerate code
$('head').append('<script>' + final_code + '; console.log(JSON.stringify(myobject));</script>');
This is really sloppy in a way, and has all the same problems as an eval() based solution, but if you just need to parse/reformat the data one time, then the above should get you a clean JSON copy of the JS object.
Depending on what else is in the JSON, you could simply do a string replace and replace '{' with '{"' and ':' with '":'.

Categories