json object deserialize issue typescript - javascript

As part of my project, I need to write some model data to JSON object and download it to file.
then I need to load that file and deserialize the JSON to model object.
That part is not working
demo project
https://stackblitz.com/edit/angular-wpg5gx
for repro, click on the export button you will get JSON file downloaded and try to import the exported file
expected
{"name":"usa","orgAddress1":"123 broadway","orgAddress2":"2D","city":"new york","system":[{"name":"sap"},{"name":"sap"},{"name":"sap"},{"name":"sap"},{"name":"sap"},{"name":"sap"},{"name":"sap"},{"name":"sap"},{"name":"sap"},{"name":"sap"}]}
actual result:
Partner {0: "{", 1: """, 2: "n", 3: "a"…}
0: "{"
1: """
10: "s"
100: "a"
101: "p"
102: """
103: "}"
104: ","
105: "{"
106: """
107: "n"
108: "a"
109: "m"
11: "a"
110: "e"
...................

Update your conversions to the following
let json = fileReader.result.toString();
let obj = JSON.parse(json);
var convert = Object.assign(new Partner(), obj);
That should get you what you're looking for.

You are calling JSON.stringify() on a string before parsing it. If you remove your JSON.stringify() call, it will work as expected.
let object = JSON.parse(fileReader.result as string);

Related

array every() with includes() issues

Hey people so i've spent a bit too much time trying to find a solution for this and I'd like to know if anyone can help me.
So the problem is, I have 2 arrays, first one with multiple words from an address and another one I built with word I entered in an input, it is returning true if I put the exact same word in the input as it is in the string array but I would like it to return true if it partially match too, for example I have "CENTER" and "RACHEL" in the array of string if I write "CEN EL in the input because it would partially match 2 of the array elements
here's the code i've been trying to put together
function checker(arr, words) {
return words.every(v => arr.includes(v));
}
this.shippingAddress.forEach(address => {
const stringBuild = `${address.name} ${address.display_address} ${address.phone}`;
const arrayString = stringBuild.split(' ');
if (checker(arrayString, words)) {
_results.push(address);
}
});
An example of input would be for the array arrayString:
[
0: "CENTER"
1: "MANIKI"
2: "BRUCHESI"
3: "2225,"
4: ""
5: "STREET"
6: "RACHEL"
7: "EAST,"
8: "CITY"
9: "STUFF,"
10: "STUFF"
11: "STUFF"
12: "STUFF"
13: "STUFF"
]
for the array words:
[
0: "CEN"
1: "EL"
]
and the output would be true because CEN and EL passing in the checker would be included in the first array but it only work if I put the full words in
If I understand correctly, you want to return true if every word in the array is partially (or totally) matched?
For every word that must be matched, I would test the array of typed words, and see if at least one of the typed words partially matches the target. I'd use a regex, and also make it case-insensitive with "i" :
const checkArray = ["center","rachel"];
const isOK = (typedWords) => checkArray.every( word1 => typedWords.some( word2 => new RegExp(word2, "i").test(word1)))
console.log(isOK([ "ent" , "rac" ]))
console.log(isOK([ "AaAa" , "BbBb" ]))

How to preserve all leading white spaces when splitting the content of a FileReader in JavaScript?

I am trying to read in a python file and split the lines into elements of an array. I am able to read and split the file content, however sometimes the leading white space for some of the elements gets removed.
Is there a way to split the file while making sure to retain all of the white spaces?
Here is my code to read in the file:
reader = new FileReader();
reader.onload = function (progressEvent)
var lines = file.split("\n");
Here is an example input:
def main():
print(1)
print(2)
def main2():
print(3)
#test
Here is the expected output:
0: "def main():"
1: " print(1)"
2: " print(2)"
3: "def main2():"
4: " print(3)"
5: " #test"
Here is the real output:
0: "def main():"
1: "print(1)"
2: "print(2)"
3: "def main2():"
4: "print(3)"
5: "#test"

How to fetch Digits from a String in javascript?

I have a following string in javascript:
var xyz= "M429,100L504.5,100L504.5,106L580,106L570,98M580,106L570,114";
I want to fetch the numbers and store it in an array.
I tried following code:
var x=xyz.match(/\d+/g);
And I got the following output:
0: "429"
1: "100"
2: "504"
3: "5"
4: "100"
5: "504"
6: "5"
7: "106"
8: "580"
9: "106"
10: "570"
11: "98"
12: "580"
13: "106"
14: "570"
15: "114"
As you can see the floating point values such as 504.5 has come up seperately.
How can I fetch this properly?
You can simply change your regex to this one :
var x=xyz.match(/[0-9.]+/g);
It will allow you to capture the number and the float as well.
=> http://www.regexr.com/3b46a
You can change your regEx to this to get floating point values also
var x = xyz.match(/\d+\.*\d/g)
Try this one.
var x=xyz.match(/\d+(\.\d+)?/g);

How to escape a JSON object to feed into a JavaScript function?

Really struggling with this one! I'm building an Android and iPhone application that shows a WebView (UIWebView on iOS). The WebView has an HTML page loaded in it which contains a simple JavaScript function defined as follows:
function parseJson(input)
{
alert("start of parseJson(...) JavaScript method");
var parsedJson = JSON.parse(input);
alert("end of parseJson(...) JavaScript method");
}
What I want to do is to call my parseJson(input) JavaScript function from the Android/iOS client passing in a string as the input parameter. This is done as follows for Xamarin.Android:
string json = "{}"
myWebView.LoadUrl ("javascript:parseJson(\"" + json + "\")"));
And as follows for Xamarin.iOS:
string json = "{}"
myWebView.EvaluateJavascript ("parseJson(\"" + json + "\")");
Up to here, this works fine. No problem. The JavaScript function is called and executes. Also, I know I have to double-escape the quotation-mark character in my string, as follows:
string json = "{\\\"key\\\":\\\"value\\\"}";
This also works fine. The JavaScript function is called and executes. Double escaping "\r" and "\n" (to "\\\r" and "\\\n") also works. However, if the JSON string contains a "\\", "\b", "\t" or "\f", then the JSON.parse(...) call in my JavaScript function falls over (even if the character is double-escaped).
Any ideas on how I can reliably escape my JSON string from within the client before I feed it into my JavaScript function?
Turns out I have to escape the parameters to be fed into my JavaScript function something as follows:
string EscapeJavaScriptFunctionParameter(string param) {
char[] chars = param.ToCharArray();
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < chars.Length; i++)
{
switch (chars [i]) {
case '\\':
sb.Append ("\\\\");
break;
case '\n':
sb.Append ("\\n");
break;
case '\r':
sb.Append ("\\r");
break;
case '\b':
sb.Append ("\\b");
break;
case '\f':
sb.Append ("\\f");
break;
case '\t':
sb.Append ("\\t");
break;
default:
sb.Append (chars[i]);
break;
}
return sb.ToString ();
}
This is not a complete escape method but just demonstrates how to escape the most common JavaScript special characters.
Using this method, I call my JavaScript function from my Android project as follows:
string json = "{\"key\":\"value\"}";
string escapedJson = EscapeJavaScriptFunctionParameter(json);
myWebView.LoadUrl ("javascript:parseJson(JSON.stringify(" + escapedJson + "))");
And from my iOS project as follows:
string json = "{\"key\":\"value\"}";
string escapedJson = EscapeJavaScriptFunctionParameter(json);
myWebView.EvaluateJavascript ("parseJson(JSON.stringify(" + escapedJson + "))");
What happens if you try something like: (or for cases that don't work for you)
myWebView.EvaluateJavascript("parseJson('{\"key\":\"value\"}')");
JSON.stringify() looks useful too in your case:
myWebView.EvaluateJavascript("parseJson(JSON.stringify({key:value}))");

Error "Uncaught SyntaxError: Unexpected token with JSON.parse"

What causes this error on the third line?
var products = [{
"name": "Pizza",
"price": "10",
"quantity": "7"
}, {
"name": "Cerveja",
"price": "12",
"quantity": "5"
}, {
"name": "Hamburguer",
"price": "10",
"quantity": "2"
}, {
"name": "Fraldas",
"price": "6",
"quantity": "2"
}];
console.log(products);
var b = JSON.parse(products); //unexpected token o
Open console to view error
products is an object. (creating from an object literal)
JSON.parse() is used to convert a string containing JSON notation into a Javascript object.
Your code turns the object into a string (by calling .toString()) in order to try to parse it as JSON text.
The default .toString() returns "[object Object]", which is not valid JSON; hence the error.
Let's say you know it's valid JSON, but you’re are still getting this...
In that case, it's likely that there are hidden/special characters in the string from whatever source your getting them. When you paste into a validator, they are lost - but in the string they are still there. Those characters, while invisible, will break JSON.parse().
If s is your raw JSON, then clean it up with:
// Preserve newlines, etc. - use valid JSON
s = s.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// Remove non-printable and other non-valid JSON characters
s = s.replace(/[\u0000-\u0019]+/g,"");
var o = JSON.parse(s);
It seems you want to stringify the object, not parse. So do this:
JSON.stringify(products);
The reason for the error is that JSON.parse() expects a String value and products is an Array.
Note: I think it attempts json.parse('[object Array]') which complains it didn't expect token o after [.
I found the same issue with JSON.parse(inputString).
In my case, the input string is coming from my server page (return of a page method).
I printed the typeof(inputString) - it was string, but still the error occurs.
I also tried JSON.stringify(inputString), but it did not help.
Later I found this to be an issue with the new line operator [\n], inside a field value.
I did a replace (with some other character, put the new line back after parse) and everything was working fine.
JSON.parse is waiting for a String in parameter. You need to stringify your JSON object to solve the problem.
products = [{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}];
console.log(products);
var b = JSON.parse(JSON.stringify(products)); //solves the problem
You should validate your JSON string here.
A valid JSON string must have double quotes around the keys:
JSON.parse({"u1":1000,"u2":1100}) // will be ok
If there are no quotes, it will cause an error:
JSON.parse({u1:1000,u2:1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
Using single quotes will also cause an error:
JSON.parse({'u1':1000,'u2':1100})
// error Uncaught SyntaxError: Unexpected token ' in JSON at position 1
products = [{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}];
change to
products = '[{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}]';
If there are leading or trailing spaces, it'll be invalid.
Trailing and leading spaces can be removed as
mystring = mystring.replace(/^\s+|\s+$/g, "");
Source: JavaScript: trim leading or trailing spaces from a string
Here's a function I made based on previous replies: it works on my machine but YMMV.
/**
* #description Converts a string response to an array of objects.
* #param {string} string - The string you want to convert.
* #returns {array} - an array of objects.
*/
function stringToJson(input) {
var result = [];
// Replace leading and trailing [], if present
input = input.replace(/^\[/, '');
input = input.replace(/\]$/, '');
// Change the delimiter to
input = input.replace(/},{/g, '};;;{');
// Preserve newlines, etc. - use valid JSON
//https://stackoverflow.com/questions/14432165/uncaught-syntaxerror-unexpected-token-with-json-parse
input = input.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// Remove non-printable and other non-valid JSON characters
input = input.replace(/[\u0000-\u0019]+/g, "");
input = input.split(';;;');
input.forEach(function(element) {
//console.log(JSON.stringify(element));
result.push(JSON.parse(element));
}, this);
return result;
}
One other gotcha that can result in "SyntaxError: Unexpected token" exception when calling JSON.parse() is using any of the following in the string values:
New-line characters.
Tabs (yes, tabs that you can produce with the Tab key!)
Any stand-alone slash \ (but for some reason not /, at least not on Chrome.)
(For a full list see the String section here.)
For instance the following will get you this exception:
{
"msg" : {
"message": "It cannot
contain a new-line",
"description": "Some discription with a tabbed space is also bad",
"value": "It cannot have 3\4 un-escaped"
}
}
So it should be changed to:
{
"msg" : {
"message": "It cannot\ncontain a new-line",
"description": "Some discription with a\t\ttabbed space",
"value": "It cannot have 3\\4 un-escaped"
}
}
Which, I should say, makes it quite unreadable in JSON-only format with larger amount of text.
My issue was that I had commented HTML in a PHP callback function via Ajax that was parsing the comments and return invalid JSON.
Once I removed the commented HTML, all was good and the JSON was parsed without any issues.
When you are using the POST or PUT method, make sure to stringify the body part.
I have documented an example here at
https://gist.github.com/manju16832003/4a92a2be693a8fda7ca84b58b8fa7154
[
{
"name": "Pizza",
"price": "10",
"quantity": "7"
},
{
"name": "Cerveja",
"price": "12",
"quantity": "5"
},
{
"name": "Hamburguer",
"price": "10",
"quantity": "2"
},
{
"name": "Fraldas",
"price": "6",
"quantity": "2"
}
]
Here is your perfect JSON content that you can parse.
The only mistake is you are parsing an already-parsed object, so it's throwing an error. Use this and you will be good to go.
var products = [{
"name": "Pizza",
"price": "10",
"quantity": "7"
}, {
"name": "Cerveja",
"price": "12",
"quantity": "5"
}, {
"name": "Hamburguer",
"price": "10",
"quantity": "2"
}, {
"name": "Fraldas",
"price": "6",
"quantity": "2"
}];
console.log(products[0].name); // Name of item at 0th index
If you want to print the entire JSON content, use JSON.stringify().
products is an array which can be used directly:
var i, j;
for(i=0; i<products.length; i++)
for(j in products[i])
console.log("property name: " + j, "value: " + products[i][j]);
Now apparently \r, \b, \t, \f, etc. aren't the only problematic characters that can give you this error.
Note that some browsers may have additional requirements for the input of JSON.parse.
Run this test code in your browser:
var arr = [];
for(var x=0; x < 0xffff; ++x){
try{
JSON.parse(String.fromCharCode(0x22, x, 0x22));
}catch(e){
arr.push(x);
}
}
console.log(arr);
Testing on Chrome, I see that it doesn't allow JSON.parse(String.fromCharCode(0x22, x, 0x22)); where x is 34, 92, or from 0 to 31.
Characters 34 and 92 are the " and \ characters respectively, and they are usually expected and properly escaped. It's characterss 0 to 31 that would give you problems.
To help with debugging, before you do JSON.parse(input), first verify that the input doesn't contain problematic characters:
function VerifyInput(input){
for(var x=0; x<input.length; ++x){
let c = input.charCodeAt(x);
if(c >= 0 && c <= 31){
throw 'problematic character found at position ' + x;
}
}
}
Oh man, solutions in all previous answers didn't work for me. I had a similar problem just now. I managed to solve it with wrapping with the quote. See the screenshot. Whoo.
Original:
var products = [{
"name": "Pizza",
"price": "10",
"quantity": "7"
}, {
"name": "Cerveja",
"price": "12",
"quantity": "5"
}, {
"name": "Hamburguer",
"price": "10",
"quantity": "2"
}, {
"name": "Fraldas",
"price": "6",
"quantity": "2"
}];
console.log(products);
var b = JSON.parse(products); //unexpected token o
The error you are getting, i.e., "unexpected token o", is because JSON is expected, but an object is obtained while parsing. That "o" is the first letter of word "object".
It can happen for a lot of reasons, but probably for an invalid character, so you can use JSON.stringify(obj); that will turn your object into a JSON, but remember that it is a jQuery expression.
In my case there are the following character problems in my JSON string:
\r
\t
\r\n
\n
:
"
I have replaced them with other characters or symbols, and then reverted back again from coding.
This is now a JavaScript array of objects, not JSON format. To convert it into JSON format, you need to use a function called JSON.stringify().
JSON.stringify(products)
Why do you need JSON.parse? It's already in an array-of-object format.
Better use JSON.stringify as below:
var b = JSON.stringify(products);
The mistake I was doing was passing null (unknowingly) into JSON.parse().
So it threw Unexpected token n in JSON at position 0.
But this happens whenever you pass something which is not a JavaScript Object in JSON.parse().
Use eval. It takes JavaScript expression/code as string and evaluates/executes it.
eval(inputString);

Categories

Resources