why does JSON.stringify() adds extra ' ' around the object [duplicate] - javascript

This question already has an answer here:
What does "double quotes" mean in chrome ? (This is weird)
(1 answer)
Closed 3 years ago.
what I understand that JSON format is similar as objects in JavaScript just keys are represented as string , hence:
{name:'John'} \\is JavaScript object
{"name":"John"} \\is Json
however when i try this
`var obj = { name: "John", age: 30, city: "New York" };
var myJSON = JSON.stringify(obj);`
I get '{"name":"John","age":30,"city":"New York"}'
why this extra ' ' warping around the object?

There is no extra ' wrapping the object (not that it is an object, it is a JSON representation of an object).
var obj = { name: "John", age: 30, city: "New York" };
var myJSON = JSON.stringify(obj);
var textNode = document.createTextNode(myJSON);
document.body.appendChild(textNode);
You might be using a debugging tool that is using ' characters to inform you that the value of myJSON is a string (because that's the point of JSON.stringify: It takes a JS variable and makes a JSON text out of it, then it stores that text in a string and makes it available to JS).

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

Formating JSON object, From single quotation to double

I'm using a data-set given to me and I'm trying to parse (Using Node) the JSON objects returned to me,
Turns out they are all using single quotations, and from my research JSON uses double.
Example of a JSON object I get returned!
{
'cast_id': 16,
'character': 'Alexander Haig',
'credit_id': '52fe43c59251416c7501d72d',
'gender': 2,
'id': 6280,
'name': 'Powers Boothe',
'order': 2,
'profile_path': '/3nNL6AvMAYq0BmHKM79RnRZVq3i.jpg'
},
I've been using str.replace() to sort the objects out before JSON.parse() which was fine untill I found objects like this one
{
'cast_id': 26,
'character': '"Jack Jones"',
'credit_id': '52fe43c59251416c7501d751',
'gender': 2,
'id': 6840,
'name': 'Larry Hagman',
'order': 16,
'profile_path': '/40PVsGp5Wp5kbUhAefLHqjqbarc.jpg'
},
Notice the 'character': '"Jack Jones"', This has been causing me all types of issues!
I there a library that will help parse this all for me?
Am I missing something?
FYI:
I can't access each record as the JSON objects aren't stored separately instead, as a long string including up to 60 JSON objects.
I currently have a function that helps parse the data:
function formatJSON(cast) {
cast = cast.replace(/(\w) "(\w)/g, "$1 *$2");
cast = cast.replace(/(\w)" /g, "$1* ");
cast = cast.replace(/': '/g, '": "');
cast = cast.replace(/', '/g, '", "' );
cast = cast.replace(/'},/g, '"},');
cast = cast.replace(/': /g, '": ');
cast = cast.replace(/, '/g, ', "');
cast = cast.replace(/{'/g, '{"');
cast = cast.replace(/: None}/g, ': "None"}');
cast = cast.replace(/'}/g, '"}');
return cast;
}
Update
The data reportedly extracts nicely in python as a dictionary using ast.literal_eval()
By default, you don't need to replace a string which is wrapped by double quotes with the same string contains single quote. There is no difference between 'Jack Jones' and "Jack Jones" since all of them are string.
In your case, you're trying to replace something like this example:
var str = '\'Jack Jones\''.replace(/'/g, '"');
console.log('\'' + str + '\'');
So, if you want to wrap all of properties names and values by double quotes, you can use JSON.stringify and JSON.parse like this:
var cast = {
'cast_id': 16,
'character': 'Alexander Haig',
'credit_id': '52fe43c59251416c7501d72d',
'gender': 2,
'id': 6280,
'name': 'Powers Boothe',
'order': 2,
'profile_path': '/3nNL6AvMAYq0BmHKM79RnRZVq3i.jpg'
};
cast = JSON.stringify(cast);
cast = JSON.parse(cast);
console.log(cast);

How to convert JSON object to a different format [duplicate]

This question already has answers here:
JSON.stringify without quotes on properties?
(16 answers)
Closed 3 years ago.
I have a JSON object like this
{
"name": "Test Name",
"age": 24
}
Is there a way I can convert this to a String in a format like
{
name: "Test Name",
age: 24
}
The JSON will be of varying lengths with different properties.
Right now, I am doing this as shown below. This can get too long and messy for larger and more complex JSON objects. I need to know if there is an easier and cleaner solution for this.
let cypherQueryObject = '{';
cypherQueryObject += ` name: "${user.name}";
if (user.age) { cypherQueryObject += `, age: "${user.age}"` };
cypherQueryObject = '}';
The solution that you are looking for is little different than what someone expect. JavaScript's JSON.stringify() generates JSON string and a valid JSON contains " (double quotes only) around keys.
In your case, you are trying to use the JSON string without " around keys. So here is a little simple process to do that. Here I am assuming that you are going to use this in simple kind of JSON strings where the value part of any key don't have key: kind of things then it will work fine of bigger JSONs too.
If it is not like that then you will need to improve the find & replace utility in more efficient form. Regular expressions are great for this work.
Here I have tried to solve your problem like this.
I have used NODE REPL to execute statements so please ignore undefined returned by default.
>
> let o = {
... "name": "Test Name",
... "age": 24
... }
undefined
>
> s = JSON.stringify(o)
'{"name":"Test Name","age":24}'
>
> s = JSON.stringify(o, undefined, 4)
'{\n "name": "Test Name",\n "age": 24\n}'
>
> console.log(s)
{
"name": "Test Name",
"age": 24
}
undefined
>
> for(k in o) {
... s = s.replace("\"" + k + "\":", k + ':')
... }
'{\n name: "Test Name",\n age: 24\n}'
>
> console.log(s)
{
name: "Test Name",
age: 24
}
undefined
>
you can have a look at this as well.

understanding Javascript objects syntax [duplicate]

This question already has answers here:
Javascript object Vs JSON
(5 answers)
Closed 8 years ago.
<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
"lastName" : "Doe",
age : 50,
"eyeColor" : "blue"
};
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName + " is " + person.age + " years old.";
</script>
</body>
</html>
result is ---> John Doe is 50 years old.
here whether the property firstName,"lastName" is enclosed in quotes or not the code still works.but what is the technical difference and in which cases it won't work
for example in JSON the person object's firstName property is invalid json syntax unless the quotes are present.
but javascript allows either syntax to work
Javascript object may have key names enclosed in quotes or without quotes. This feature has more significance when the key name contains a special character like -, white space etc.
Foe example
var person = {
first Name : "John", // Will not work
"last Name" : "Doe", // Will work
age : 50,
"eyeColor" : "blue"
};

setting variable to a JSON string (not object) [duplicate]

This question already has answers here:
Creating multiline strings in JavaScript
(43 answers)
Closed 8 years ago.
I'm simply trying to set this JSON string to a variable but I'm not doing something right, not escaping something right
var stringJson= '{
"Status": {
"Code": 3002,
"Message": "something",
"Succeeded": false
}
}'
it's not liking the brackets, doesn't treat it as a string and is treating it as actual js code
1) you were missing the closing bracket for "Status",
2) You cannot have line breaks in javascript strings without escaping them:
var stringJson= '{\
"Status": {\
"Code": 3002,\
"Message": "something",\
"Succeeded": false\
}\
}';
Better yet you should just create an object and JSON.stringify it:
var obj = { Status : { Code : 3002, Message : 'something', Succeeded : false } };
var stringJson = JSON.stringify(obj);

Categories

Resources