How to parse javascript object string in javascript? [duplicate] - javascript

This question already has answers here:
Parsing "relaxed" JSON without eval
(6 answers)
Closed 6 years ago.
I have a string representation of an object, in a template string, like this
const obj = `
{
namespace: 'ignored',
state: {}
}
`
Now I want to parse that into an object, but JSON.parse throws an error.
JSON.parse(obj)
//=> Uncaught SyntaxError: Unexpected token n in JSON at position 13(…)
thats because JSON.parse expect a json string like this
const obj = `
{
"namespace": "ignored",
"state": {}
}
`
Now, I can't manually change my obj object, because is an user input, and can be way more complex. So, is there any way to parse it? before using JSON.parse, maybe some regex, or maybe some other method better than JSON.parse?
Any help is appreciated.

You could do a few things.
Use a proper parser.
Use eval().
For most applications, particularly if there is any user-input there that will end up on other user's computers, eval()'s a terrible idea. Probably only useful here for a throwaway script or similar.
For parsing, define its input grammar, parse it into a tree structure and then directly create the JavaScript object you need. Since it looks like actual JavaScript code, you could use an existing parser and it will be much easier.

Related

Converting formdata type string into JS object [duplicate]

This question already has answers here:
How to convert URL parameters to a JavaScript object? [duplicate]
(34 answers)
Closed 5 months ago.
I am using ajax to send FormData and receiving the output in the following format
Result=A&Status=Approved&Error=&ErrorCode=00000
I want to convert the same into a JS object (key value pair)
e.g.
{Result: "A", Status: "Approved", Error: "", ErrorCode: "00000"}
I can do that using string split and other string functions or regex but since the output format is consistent i was wondering if this is a known data type and if yes is there a way to convert it using native functions?
You can use Object.fromEntries in conjunction with the URLSearchParams constructor.
const obj = Object.fromEntries(new URLSearchParams(
'Result=A&Status=Approved&Error=&ErrorCode=00000'));
console.log(obj);
Take a look at new URLSearchParams(), it should be a way better solution than string manipulation.

JavaScript Acces Object Prop [duplicate]

This question already has an answer here:
How to access object property beginning with a number (SyntaxError: Unexpected identifier)
(1 answer)
Closed 2 years ago.
I have the following object:
If I try to get the value from it by using let result = object.3h I get the following error
error: `Parsing error: Identifier directly after number`.
Identifiers in Javascript can’t start with a number (You can check the exact rules at the link provided.
When dealing with object properties, you can use string literals for defining properties that won’t follow this rule (Which might also happen when dealing with JSON objects)
In order to access this properties you need to use a property accessor
On your case:
day.rain[‘3h’]
you need to use bracket notation
correct
object["3h"]
incorrect
object.3h
const object = { "3h": 0.44 }
console.log(object["3h"])

Pase json in javascript [duplicate]

This question already has answers here:
Safely turning a JSON string into an object
(28 answers)
Closed 7 years ago.
I am trying to parse json in JavaScript
var str = '{"id-1": "www.er.co.uk","id-2": "www.wer.co.uk","id-3": "wer.wer.com","id-4": "www.wwaer.co.uk"}';
var divWebsite = JSON.parse(str);
i am getting error (fiddle)
Uncaught SyntaxError: Unexpected token o
While at the same time my json is valid as you can see here http://jsonlint.com/ (sorry you will need to copy and past json)
That's not JSON. You can see the difference:
http://jsfiddle.net/05dn7mpa/2/
So if you have an string with a json you can parse it. If you've got the propper vanilla object it's parsed !
var divWebsite = JSON.parse('{ "id-1": "www.er.co.uk", "id-2": "www.wer.co.uk", "id-3": "wer.wer.com", "id-4": "www.wwaer.co.uk"}');
In this case you need to pass a string to JSON.parse
HTML
<div id="parsed"></div>
JS
var divWebsite = JSON.parse('{"id-1": "www.er.co.uk","id-2": "www.wer.co.uk","id-3": "wer.wer.com","id-4": "www.wwaer.co.uk"}');
document.getElementById('parsed').innerHTML = divWebsite['id-1'];
JSFIDDLE
What you pass to JSON.parse() is not a string, that's why. You pass an object. In a typical scenario you want JSON.parse to return that object. What you should pass is a string.
If you want to get a json string out of that object use JSON.stringify()

Is there something like object.toJSON in ES6? [duplicate]

This question already has answers here:
Convert JS object to JSON string
(23 answers)
Closed 7 years ago.
I'm using ES6 I transpile using Babel into ordinary JavaScript.
I want to serialise objects into JSON format and am wondering if ES5,ES6 offers a convenient function to do so.
For Maps and Sets there is a toJSON()-function proposed in ES7
You can use JSON.stringify and pass any kind of variable to it (given that it can be represented in JSON).
It works in all current browsers; in case you need a fallback for a really old browser, you can use Crockford's JSON-js.
However, keep in mind that, regarding objects, only public properties are serialized. There's no a generic way to serialize function variables etc. on the fly.
This is why some special object types provide a toJSON or similar method. In order to use such a function for arbitrary objects, you must pass a function as second parameter to JSON.stringify which checks for the existence of a toJSON function.
For example, the following should work (not tested, just from the top of my mind):
var jsonString = JSON.stringify(someLargeObject, function(key, value){
return (value && typeof value.toJSON === 'function')
? value.toJSON()
: JSON.stringify(value);
});
If your someLargeObject contains a sub-object with a toJSON method, this code would use the object's implementation, otherwise use JSON.stringify.

isJSON in javascript, without try/catch [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to check if a string is a valid JSON string in JavaScript without using Try/Catch
The question was already asked here : How to check if a string is a valid JSON string in JavaScript without using Try/Catch. No valid answer was given, even the validated one wasn't answering the question.
So it seems the only way to not doing this using try/catches is via regexps; the regexp given in one of the answers was only validating against eval, so a simple string like "2001-05-06" would pass the regexp, even though it's not JSON.
So has anyone a good regexp to validate against a well formed JSON string ?
Using a regex instead of a try/catch is replacing a correct solution with a non working hack.
The link you give suggests to change the JSON parsing code that you can modify to not throw an exception. I would suggest replacing in json_parse.js the following code
error = function (m) {
// Call error when something is wrong.
throw {
name: 'SyntaxError',
message: m,
at: at,
text: text
};
},
by the call of a callback you would provide.
But to be frank, my most reasonable suggestion would be to use try/catch. That's the best tool you have here. Note that my JSON.parse modification "suggestion" supposes to manage the break from all loops/recursions, which is precisely what an exceptions does.
from link try this
var jsonData = '{"1":"test"}';
if (/^[\],:{}\s]*$/.test(jsonData.replace(/\\["\\\/bfnrtu]/g, '#'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
alert('ok');
}else{
alert('no');
}

Categories