Replace \" with " in Javascript - javascript

I have a JSON from my web server that I obtain from a XMLHttpRequest.
The data has the following form when I print it out using
var data = this.responseText;
console.log("data=" + JSON.stringify(data));
data=[{\"day\":0,\"periods\":[\"0xffffffffffff\"]}]
I process the JSON using jquery but I'm getting an error:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"day":0,"periods":["0xffffffffffff"]}]
I'm assuming the problem is due to the escaping of the quotes as if I hard code data to [{"day":0,"periods":["0xffffffffffff"]}]
I don't get the error.
I've tried various ways of getting rid of the escape but without success:
data = data.replace(/\\/g, "");
Does not modify the string at all;
I found a function from another thread, replaceAll, but this:
var newData = data.replaceAll("\\","");
..made no difference either.
Trying to replace \" with ' then replacing the ' with " just returns me to \"
var newData = data.replaceAll("\"","'");
now newData = [{'day':0,'periods':['0xffffffffffff']}]
newData = newData.replaceAll("'","\"");
and it's back to [{\"day\":0,\"periods\":[\"0xffffffffffff\"]}]
Trying to process with single quote, i.e. [{'day':0,'periods':['0xffffffffffff']}] gives me the same Uncaught TypeError message.
Any ideas how I can solve this?
Thanks.

The error is that you are using JSON.stringify on a string. Have an exact look on this.responseText - responseText - that you are using as property. Just change it to
var data = JSON.parse(this.responseText);
console.log("data=" + data);

Related

Node-Red: Parse JavaScript Object with Double value

I am using node-RED to call in data from a robot. In the debug window it says it is a 'msg: Object', and when I copy it to a notepad it takes the format: {"topic":"","payload":27.659992218017578,"_session":{"type":"tcp","id":"0151ff7339437ec6"},"_msgid":"6a6897605a523366"}
I am also not sure if this is a JSON object or not, as I see examples with '' around the brackets.
I am trying to use the function node within node-red to parse this to attain the "payload" value. However, it keeps returning as undefined.
I am using the script:
var json =msg.payload;
var obj = JSON.parse(json);
msg.payload = console.log(obj.payload);
return msg;
I am a beginner to javascript and JSON, however I have tried searching and all examples only have integers as the parsing value. I am also unsure if the value name itself 'payload' is causing an issue. I have also attempted to stringify and using 'getDouble' but had no luck, which I owe to my lack of experience.
I appreciate any guidance.
You don't need to do anything. The value of msg.payload is already a double.
Without a lot more context of what you are trying to do there isn't anything else that we can say here.
After the node that gets the above information (the data in {} in the question}, I then used the function node to construct the message that I wanted to sent to the IIOT platform. I did
const str = msg.payload
msg.payload = " ," + str
// where the text I required was in " "
return msg
Also this works:
msg.payload = "," + msg.payload
return msg
And then I used the MQTT output node to publish this to the IIOT platform

Generating fully valid JSON with client-side JavaScript

So I am trying to create a JSON explorer / editor. I am able to parse the initial JSON into the div and format it how I like.
this is the function i use to loop through the initial JSON
_iterate(_tab, raw_json){
var tab = _tab;
tab++;
for(var key1 in raw_json){
var data_type = typeof raw_json[key1];
var d = String(raw_json[key1])
if(d == String){
d = "String";
}
if(d == Number){
d= "Number"
}
if(data_type == "object" || data_type == "array"){
this.input.append(`<json-tab tab-width="${tab}"></json-tab><div class="json-editor-input-container-2 -je-${data_type}">'<span class="-je-key">${key1}</span>' :{</div></br>`)
this._iterate(tab, raw_json[key1])
}else{
this.input.append(`<div class="json-editor-row"><json-tab tab-width="${tab}"></json-tab><div class="json-editor-input-container-2">'<span class="-je-key">${key1}<span>' : '<div class="json-editor-input -je-${data_type}" contenteditable="true" for="{key: '${key1}', data: '${d}'}"></div>', </div></br></div>`)
}
}
this.input.append(`<json-tab tab-width="${tab -1}"></json-tab>},</br>`)
}
in order to save the JSON I was going to retrieve the JSON from the text of the div using
getJSON(){
var json_text = this.input.text().slice(0, -1)
return JSON.parse(`"${json_text}"`)
}
right now this is able to be parse by JSON.parse(); but when i want to console.log(getJSON()[0]) this returns {
am i not formating the JSON correctly. a live example of this can be found here
First, your console.log result doesn't make sense. A parsed JSON object is now usable in JavaScript and, if has (only) properties x and y, would result in undefined when requesting property 0 as you have. It looks like your call to console.log was to a different (earlier?) version of the getJSON() function, where it returned the raw string, and in that case it makes sense that you're just retrieving the first character of the JSON text: "{".
But then, assuming the version of getJSON() as written, it would actually throw a parse exception:
VM1511:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 1
Looking at your site, I was able to do, in the console:
jsonString = $('json-editor').text()
// value: "{'partName' : '', 'partRevision' : '', ..."
That is illegal JSON. JSON specifies (only) the quotation mark " for strings (Unicode/ASCII 0x22) on page 7 of its specification.
The fact that 'partName' is legal as a JavaScript string literal is irrelevant but perhaps confusing.
As a minor style point, simplify JSON.parse(`"${json_text}"`) to JSON.parse(json_text).
#BaseZen's answer was very helpful for me to understand what was going wrong with my code. My JSON was incorrectly formatted even though online linters say its correct. Along with what BaseZen pointed out, JSON.parse() will not work with trailing commas. To fix this:
_remove_trailing_commas(json_string){
var regex = /\,(?!\s*?[\{\[\"\'\w])/g;
return json_string.replace(regex, '');
}
I found this information at SO post JSON Remove trailiing comma from last object
SO user Dima Parzhitsky's answer was what helped me also figure out this question.

Native javascript JSON.parse throws typeError

I'm stuck parsing a JSON string correctly. There seems no way to use JSON.parse.
eval succeeds, but I want the secure way :)
I query a website in an aspx Service class this way:
[OperationContract]
public String queryNominatim(String request)
{
string uri = "http://nominatim.openstreetmap.org/search.php?q=" + request + nominatimParams;
string response = "from ajax";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
req.UserAgent = HttpContext.Current.Request.UserAgent;
req.Method = "POST";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Encoding enc = Encoding.GetEncoding(resp.CharacterSet);
StreamReader reader = new StreamReader(resp.GetResponseStream(), enc);
response = reader.ReadToEnd();
reader.Close();
return response;
}
Where request is a street name like "windmühlenstraße".
The full uri is "http://nominatim.openstreetmap.org/search.php?q=windmühlenstraße&format=json&countrycodes=de&addressdetails=1"
The answer is a JSON string which i just want to deliver to the calling javascript code. http://jsonlint.com/ validates that as correct.
But in javascript, this code
arr = JSON.Parse(response);
throws an Exception:
TypeError: JSON.Parse is not a function
This is what I found out so far:
JSON.Parse is existing and working. I tried another json-string hard-coded in javascript successfully.
arr = eval("(" + response + ")"); works as expected. The array and objects are fully accessable.
I converted the escaped unicode chars serverside to unicode chars by this:
private string DecodeEncodedNonAsciiCharacters(string value)
{
return Regex.Replace(
value,
#"\\u(?<Value>[a-zA-Z0-9]{4})",
m =>
{
return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString();
});
}
But the exception is thrown anyway.
I hardcoded copy&pasted answeres to to Javascript:
var original = "[{\"place_id\":\"2413006\",\"licence\":\"Data \u00a9 OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright\",\"osm_type\":\"node\",\"osm_id\":\"344446896\",\"boundingbox\":[\"52.3739283\",\"52.3740283\",\"9.7434778\",\"9.7435778\"],\"lat\":\"52.3739783\",\"lon\":\"9.7435278\",\"display_name\":\"6, Theaterstra\u00dfe, Mitte, Hannover, Region Hannover, Niedersachsen, 30159, Deutschland\",\"class\":\"place\",\"type\":\"house\",\"importance\":0.311,\"address\":{\"house_number\":\"6\",\"road\":\"Theaterstra\u00dfe\",\"suburb\":\"Mitte\",\"city_district\":\"Mitte\",\"city\":\"Hannover\",\"county\":\"Region Hannover\",\"state\":\"Niedersachsen\",\"postcode\":\"30159\",\"country\":\"Deutschland\",\"country_code\":\"de\"}}]";
jsObject = JSON.parse(original);
alert(jsObject[0] + ": " + jsObject[0].display_name);
which is successfull. displayname is shown.
converted and excaped unicode in json string makes no difference. Firefox displays correct letters.
in chrome the error is spelled: typeerror: undefined is not a function.
IE: typeerror: das objekt unterstützt die Eigenschaft oder Methode "parse" nicht. Meaning: Object doesn't support property or method "parse".
what is wrong? Is the copy&paste converting something, i miss?
What am I missing???
JSON.Parse does not exist in JavaScript, you want JSON.parse. Lower case p!
From what I can tell by your first code snippet arr = JSON.Parse(response);, you are attempting to use an uppercase version of JSON.parse. The second code snippet works just fine for me in all modern browsers. See documentation here. JavaScript is case-sensitive.

JSON.Parse,'Uncaught SyntaxError: Unexpected token o [duplicate]

This question already has answers here:
I keep getting "Uncaught SyntaxError: Unexpected token o"
(9 answers)
Closed 6 years ago.
I am having trouble with JSON returned from a web service. It looks like the JSON lacks quotes, but when I add quotes to the JSON, I get an error. Here is the error message: 'Uncaught SyntaxError: Unexpected token o. When I log the string to console:[object Object],[object Object]
Here is some example code that simulates the error:
//Error I am trying to solve
var jsonString = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
var myData = JSON.parse(jsonString);
$(document).ready(function() {
var $grouplist = $('#groups');
$.each(myData, function() {
$('<li>' + this.Name + '</li>').appendTo($grouplist);
});
});
Here is the same code with the single quotes around the string. It works
//Successful Javascript
var jsonString = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
var myData = JSON.parse(jsonString);
$(document).ready(function() {
var $grouplist = $('#groups');
$.each(myData, function() {
$('<li>' + this.Name + '</li>').appendTo($grouplist);
});
});
//Successful HTML
<ul id="groups"></ul>
But when I try to add quotes to the string, like I seem to need to in my real code, it fails:
//Does not work when I need to append quotes to the string:
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
jsonStringQuotes = "'" + jsonStringNoQuotes + "'";
var myData = JSON.parse(jsonStringQuotes);
$(document).ready(function() {
var $grouplist = $('#groups');
$.each(myData, function() {
$('<li>' + this.Name + ',' + this.Id + '</li>').appendTo($grouplist);
});
});
Here is the error:
log string to console:[object Object],[object Object]
data.js:809 Uncaught SyntaxError: Unexpected token '
I'm stumped. Any help appreciated! Thank you!
Without single quotes around it, you are creating an array with two objects inside of it. This is JavaScript's own syntax. When you add the quotes, that object (array+2 objects) is now a string. You can use JSON.parse to convert a string into a JavaScript object. You cannot use JSON.parse to convert a JavaScript object into a JavaScript object.
//String - you can use JSON.parse on it
var jsonStringNoQuotes = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
//Already a javascript object - you cannot use JSON.parse on it
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
Furthermore, your last example fails because you are adding literal single quote characters to the JSON string. This is illegal. JSON specification states that only double quotes are allowed. If you were to console.log the following...
console.log("'"+[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]+"'");
//Logs:
'[object Object],[object Object]'
You would see that it returns the string representation of the array, which gets converted to a comma separated list, and each list item would be the string representation of an object, which is [object Object]. Remember, associative arrays in javascript are simply objects with each key/value pair being a property/value.
Why does this happen? Because you are starting with a string "'", then you are trying to append the array to it, which requests the string representation of it, then you are appending another string "'".
Please do not confuse JSON with Javascript, as they are entirely different things. JSON is a data format that is humanly readable, and was intended to match the syntax used when creating javascript objects. JSON is a string. Javascript objects are not, and therefor when declared in code are not surrounded in quotes.
See this fiddle:
http://jsfiddle.net/NrnK5/
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
it will create json object. no need to parse.
jsonStringQuotes = "'" + jsonStringNoQuotes + "'";
will return '[object]'
thats why it(below) is causing error
var myData = JSON.parse(jsonStringQuotes);
Your last example is invalid JSON. Single quotes are not allowed in JSON except inside strings. In the second example, the single quotes are not in the string, but serve to show the start and end.
See http://www.json.org/ for the specifications.
Should add: Why do you think this: "like I seem to need to in my real code"? Then maybe we can help you come up with the solution.
Maybe what comes from the server is already evaluated as JSON object? For example, using jQuery get method:
$.get('/service', function(data) {
var obj = data;
/*
"obj" is evaluated at this point if server responded
with "application/json" or similar.
*/
for (var i = 0; i < obj.length; i++) {
console.log(obj[i].Name);
}
});
Alternatively, if you need to turn JSON object into JSON string literal, you can use JSON.stringify:
var json = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
var jsonString = JSON.stringify(json);
But in this case I don't understand why you can't just take the json variable and refer to it instead of stringifying and parsing.

Javascript replace for equal symbol

I am getting my response as following
var val = {"Type"=>"D","Number"=>33"}
From above i try to change like this
var MyArray = {"Type": "D", "Number": "33"};
for(key in MyArray)
{
alert("key " + key
+ " has value "
+ MyArray[key]);
}
I tried replace, replace all but those not working. Any suggestions?
Server side code pasted from comments...
new_transfer_header = #params['my_extra_param']
p new_transfer_header,'------------ ew_transfer_header----------,new_transfer_header.class
WebView.execute_js("replaceDeliveryWithScanUnit('#{new_transfer_header}')")
puts result as "{\"Type\"=>\"D\", \"Number\"=>\"33\"}
var val = {"Type"=>"D","Number"=>33"}
Is invalid JavaScript - there is no way to fix it within the same script/script block since it fails parsing.
Likely you need to eliminate extra HTML encoding that somone done for this chunk of script on the server.
If it is text received by some AJAX call you should be able to replace " and similar values with corresponding characters and than parse with JSON.parse.
you could use string.replace and cal eval on the result I think, but would it be better to get valid json from the server ?

Categories

Resources