Transform info in json valid [duplicate] - javascript

This question already has answers here:
Safely turning a JSON string into an object
(28 answers)
Closed 3 years ago.
Transform this result in json valid.
"{\"name\":\"log\",\"hostname\":\"denis-Latitude-E7470\",\"pid\":1007,\"level\":30,\"conextion\":\"DBA MongDB: \[32m%s\[0m\",\"msg\":\"online\",\"time\":\"2019-12-06T13:50:42.510Z\",\"v\":0}"

Just parse it via JSON.parse() to convert the string into a JSON object.
let jsonString = "{\"name\":\"log\",\"hostname\":\"denis-Latitude-E7470\",\"pid\":1007,\"level\":30,\"conextion\":\"DBA MongDB: \[32m%s\[0m\",\"msg\":\"online\",\"time\":\"2019-12-06T13:50:42.510Z\",\"v\":0}";
console.log(JSON.parse(jsonString));
let brokenJsonString = '{ "key": "<div class="coolCSS">some text</div>" }';
try {
console.log(JSON.parse(brokenJsonString));
} catch (e) {
console.log("Exception thrown when parsing.", e.toString());
}
Be careful when parsing strings because (as #Fallenreaper noted) malformed or invalid JSON is going to result in an error thrown. So wrap your JSON.parse() with try...catch statement (more about it here).
Broken/malformed can be handled with libraries like this but use them when you absolutely need it and always read the docs.

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.

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

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.

How to convert a String that looks like JSON or a JS object, to an actual JS object? [duplicate]

This question already has answers here:
How to parse JSON easily?
(3 answers)
Closed 6 years ago.
The String I am talking about was initially a part of a JS object like:
var nameVal = "Jacob";
var favNumbersVal = "{\"firstNum\":0, \"secondNum\":1, \"thirdNum\":2}";
var aJSObject = {
"name" = nameVal,
"favNumbers" = favNumbersVal
};
The variable I am interested in is favNumbersVal. Please notice that the starting and ending " around the value of favNumbersVal are the normal double quotes we put around a String whenever we define a String.
The format of the value of favNumbersVal is coming from a library dynamically.
The question is that how do I convert the value of favNumbersVal to a JS object, so that when I later convert sJSObject to JSON using JSON.stringify(), the value of aJSObject becomes a JSON object, and the value of favNumbers becomes a JSON object nested inside the aforementioned JSON object.
Using JSON.parse():
var favNumbersVal = "{\"firstNum\":0, \"secondNum\":1, \"thirdNum\":2}";
console.log(JSON.parse(favNumbersVal));

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()

How to validate a JSON String JQuery [duplicate]

This question already has answers here:
AJAX: Check if a string is JSON?
(8 answers)
Closed 9 years ago.
I tried that:
var c = $.parseJSON(something here)
and I control that:
c === undefined
This works however it throws error while trying to parse an invalid JSON string. I don't want it throw that error.
Any advices?
It's generally considered bad practice to suppress/ignore errors, instead why not use a try-catch block to capture the exception and do something with it:
try {
var c = $.parseJSON(something here);
}
catch (err) {
// Do something about the exception here
}
If you really don't need to do anything about the exception at least put a comment to that effect in your try-catch block, it'll make your code more readable when you come back to it later.

Categories