Convert normal String to Object in JavaScript? - javascript

I am getting this String as input
"countries" : "[[england, australia], [UAE, China], [UAE]]"
Requirement
I thought that, I need to transform this String into
{"countries": [["england", "australia"], ["UAE", "China"], ["UAE"]]}
Then I can convert it to Object in js using json.parse() method.
I tried various things but none seem to work.
I Tried
JSON.stringify
JSON.parse
eval
I have done this in Java but in Javascript not able to do so.
I am new to js, as in java I can easily do this JSONObject.
Any help will be appreciated, Thanks !!

This requires multiple steps:
Wrap the input in curly braces and do a JSON.parse:
const input = "\"countries\" : \"[[england, australia], [UAE, China], [UAE]]\""
const result = JSON.parse("{" + input + "}")
That gives you an object like:
{
"countries": "[[england, australia], [UAE, China], [UAE]]"
}
Then wrap the inner strings with double quotes and parse it again:
const inner = result.countries
result.countries = JSON.parse(inner.replaceAll(/([a-zA-Z]+)/g, '"$1"'))
That gives you result:
{
"countries": [
[
"england",
"australia"
],
[
"UAE",
"China"
],
[
"UAE"
]
]
}

Related

I get an object as a string. How to convert?

Using IMAP I receive an email.
But parsing, I get this:
{
from: [ "name lastname <mygmail#gmail.com>" ],
date: [ "Mon, 21 Jun 2021 13:41:51 +0500" ],
subject: [ "hello" ]
}
The catch is that this is a string, not an object at all!
I cannot take advantage of this.
How do I convert this string to an object?
JSON.parse() throws an error message:
UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token f in JSON at position 141
You get that error because in JSON notation properties should be enclosed in double quotes like this:
{
"from": [ "name lastname <mygmail#gmail.com>" ],
"date": [ "Mon, 21 Jun 2021 13:41:51 +0500" ],
"subject": [ "hello" ]
}
So, if what you get is a string like what you showed, you'll have to add these double quotes yourself (maybe with a nice and coolio regex)
As others have noted, because this is not JSON, you can't parse it as JSON. What it does appear to be is a JavaScript snippet.
In the past eval(customJavaScriptCode) would have been used for this but it is very insecure so avoid it.
A better and safer (but not bulletproof) way is to run the JavaScript in a sandbox environment. It's hard to break out of that. You do that like this:
Prefix your object with result = , the name doesn't really matter.
Execute the JavaScript in a sandbox.
Get the value of the last statement.
const vm = require('vm');
const script = new vm.Script('result = ' + `{
from: [ "name lastname <mygmail#gmail.com>" ],
date: [ "Mon, 21 Jun 2021 13:41:51 +0500" ],
subject: [ "hello" ]
}`);
const lastStatementResult = script.runInNewContext();
console.log(lastStatementResult.subject[0] == "hello");
You now have the object parsed as JS in a relatively safe way.
If you need more than just the last statement, you can do this like this:
const vm = require('vm');
const script = new vm.Script(`
var foo = "bar";
var baz = foo + "123";
`);
const context = {}; // will contain global variables from the script
script.runInNewContext(context);
console.log(context.foo + '123' === context.baz);
I was also running into this issue following the documentation to the letter. The problem is exactly how OP describes, there is a return value from one of Imap's callback functions that is shaped like an object, but does not respond to dot notation, nor JSON.parse/stringify.
The problem was using the suggested inspect property from the util node package. This is what is returning a string shaped like an object that is unusable. Instead, omit the inspect on the values you need to parse.
Original usage (straight from the docs) (bad)
stream.once('end', function() {
console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
});
My solution (good)
stream.once('end', function() {
console.log(prefix + 'Parsed header: %s', Imap.parseHeader(buffer));
});
All I did was omit the inspect. I can now assign Imap.parseHeader(buffer) to a variable and manipulate it just like a normal JS object.
I did not understand your question correctly.
Try this
JSON.stringify(JSON.parse(Object))
If error exist, Please describe your issue with more

In the javascript unable to convert string to variable

One of my requirement in the javascript, I am trying to convert the string which is passing from the database to javascript object.
Step1:
String passing from the databse:
"validator":["required","numeric","maxLength:14","{type: amountValidate}"]
Step2: Converting to javascript object using JSON.Parse() method, output as follows:
validator: Array(4)
0: "required"
1: "numeric"
2: "maxLength:14"
3: "{type: amountValidate}"
length: 4
Expected output is:
In the below code amountValidate is converting into the function by tabulator js api.
validator:["required","numeric","maxLength:14",{
type:amountValidate,
}]
Since I am applying the below function to the type:amountValidate, it should behave as a variable and it should not be in the double quotes.
var amountValidate = function(cell, value, parameters){
var regex = /^\s*-?(\d+(\.\d{1,2})?|\.\d{1,2})\s*$/
var n = value.match(regex);
if(n !== null){
return true;
}else{
return false;
}
}
Thanks in advance.
The main problem here is that your string is not a valid JSON. Should be something like:
'{"validator": ["required","numeric","maxLength:14", {"type": "amountValidate"}]}'
There are multiple json formatters/validators online, like this one, that you could use to check it.

Convert json single node value STRING to OBJECT using Angularjs

How can i convert a json node VALUE STRING to OBJECT using Angularjs. I am getting response from server values as string format. Here a node FCLASS is Name and ' "[{ .... }]" ' its value but value is string instead of array, need to remove first (") and last (") character and (/) all slashes inside value for converting array and object ' [{ ... }] '.
JSON:
{"FARE":[{
"ARRV_DATE": "2016-06-25",
"ARRV_TIME": "14:15",
"FCLASS ": "[{\"TYPE\":\"UPPER\",\"CL\":\"M2\"},{\"TYPE\":\"UPPER\",\"CL\":\"Y2\"},{\"TYPE\":\"LOWER\",\"CL\":\"S2\"}]",
"SEAT": 0,
},
{
"ARRV_DATE": "2016-06-25",
"ARRV_TIME": "16:20",
"FCLASS ": "[{\"TYPE\":\"UPPER\",\"CL\":\"J2\"},{\"TYPE\":\"UPPER\",\"CL\":\"C2\"},{\"TYPE\":\"LOWER\",\"CL\":\"D2\"}]",
"SEAT": 0,
},
{
"ARRV_DATE": "2016-06-25",
"ARRV_TIME": "19:10",
"FCLASS ": "[{\"TYPE\":\"UPPER\",\"CL\":\"H2\"},{\"TYPE\":\"UPPER\",\"CL\":\"C2\"},{\"TYPE\":\"LOWER\",\"CL\":\"O2\"}]",
"SEAT": 0,
}
}]
ng-repeat isn't looping this value because its requires only OBJECT.
HTML(angularjs)
.........
<div class="col-sm-2" ng-repeat="n in f.FCLASS">
<div>{{n.TYPE}}-{{n.CL}}</div>
</div>
.........
Any ideas. How to solve this? Thanks
Try using JSON.parse to parse the json string.
try this,
$scope.f.FCLASS=JSON.parse(YOUR_OBJECT.FCLASS);
I suggest first stringify value with
JSON.stringify(YOUR_OBJECT.FCLASS);
then convert to JSON object with
JSON.parse(YOUR_OBJECT.FCLASS);
Because stringifying will convert to string regardless of object OR array. It will perform as expected even if there will be Array in object value.
Regards

json_encode unicode escape sequences cannot display in javascript

json_encode(array($myarray1,$myarray2))
on php contains unicode escape sequences like
[{
"Panelbuilder 32":
[{
"topic_id":"34",
"forum_id":"6",
"topic_title": "Panelbuilder 32",
"topic_poster":"1",
"topic_time":"1189740810",
"topic_last_post_id":"124",
"topic_last_poster_id":"1",
"topic_last_poster_name":"vvv",
"topic_last_post_time":"1189740810",
"topic_last_post_subject":"Panelbuilder 32",
"topic_last_view_time":"1436511928",
"topic_replies":"0",
"topic_replies_real":"0",
"topic_views":"2463",
"topic_attachment":"0",
"topic_reported":"0",
"topic_first_post_id":"124",
"topic_first_poster_name":"vvv"
}]
}, {
"124":
[{
"post_id":"124",
"topic_id":"34",
"forum_id":"6",
"poster_id":"1",
"poster_ip":"192.44.136.113",
"post_time":"1189740810",
"post_approved":"1",
"post_reported":"0",
"post_username":"vvv",
"post_subject":"Panelbuilder 32",
"post_text":"\u0e23\u0e03\u0e22\u0e04\u0e23\u0083\u0e23\u0081\u0e23\u0095\u0e22\u0e04\u0e23\u0087\u0e23\u0092\u0e23\u0081\u0e22\u0e0a\u0e23\u0093\u0e22\u0e19\u0e23\u0092\u0e22\u0e0d\u0e23\u0e03\u0e22\u0e19\u0e22\u0e01\u0e23\u0092\u0e23\u0083\u0e23\u0e03\u0e22\u0e0a\u0e23\u0e09\u0e23\u0e02\u0e22\u0e1b\u0e23\u0083\u0e23\u0e01\u0e22\u0e01\u0e23\u0083\u0e23\u0081 Panelbuilder 32 \u0e22\u0e02\u0e23\u008d\u0e22\u0e07 AB",
"post_attachment":"0",
"post_edit_time":"0",
"topic_poster":"1",
"topic_time":"1189740810",
"topic_last_post_id":"124",
"topic_last_poster_id":"1",
"topic_last_poster_name":"vvv",
"topic_last_post_time":"1189740810",
"topic_last_post_subject":"Panelbuilder 32",
"topic_last_view_time":"1436511928",
"topic_replies":"0",
"topic_replies_real":"0",
"topic_views":"2463",
"topic_attachment":"0",
"topic_reported":"0",
"topic_first_post_id":"124",
"topic_first_poster_name":"vvv"
}]
}]
These unicode sequences displays in javascript like this /ue023 (backslash converted to forward slash) and cannot displays as characters.I need to display these characters on my phonegap application. Is there any solution ?
As you explained your using JSON.parse heres my solution:
var str = JSON.parse(data);
str.replace(/\//g, "\\");
Obviously however you get your field you will need to update the code above, e.g.
var new_data = str[1][124][0].post_text.replace(/\//g, "\\");

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