JSON Object Property Missing Quotation Marks? - node.js

I have a very trivial problem, and I'm having trouble finding similar questions. On my Node JS server, I prepare an object of key-value pairs. The keys that have spaces in them are converted to strings like this {'key':'value'}. However, the keys without spaces or special characters don't have quotes surrounding them. When I print it out it looks like this {key:'value'}. The problem is, when I send the response back to the client, the keys without surrounding quotes are missing from the object. So how would I surround all the keys with quotes then so that it is sent properly?

JSON Objects must follow the RFC-7159, the easiest way to get a RFC-compliant JSON object is to use JSON.stringify on the object you want to output on your server side, which is natively supported in NodeJS.

You just need to convert the response to client by converting the javascript object to JSON object.
var object = { key: 'value' };
var newObject = JSON.stringify(object);
console.log("format : ", newObject);
//the JSON.stringify() function definition, it will simply turn the object log into a JSON string.
OUTPUT:
format : '{ 'key' : 'value' }'

Related

NodeJS why is object[0] returning '{' instead of the first property from this json object?

So I have to go through a bunch of code to get some data from an iframe. the iframe has a lot of data but in there is an object called '_name'. the first key of name is 'extension_id' and its value is a big long string. the json object is enclosed in apostrophes. I have tried removing the apostrophes but still instead of 'extension_id_output' I get a single curly bracket. the json object looks something like this
Frame {
...
...
_name: '{"extension_id":"a big huge string that I need"} "a bunch of other stuff":"this is a valid json object as confirmed by jsonlint", "globalOptions":{"crev":"1.2.50"}}}'
}
it's a whole big ugly paragraph but I really just need the extension_id. so this is the code I'm currently using after attempt 100 or whatever.
var frames = await page.frames();
// I'm using puppeteer for this part but I don't think that's relevant overall.
var thing = frames[1]._name;
console.log(frames[1])
// console.log(thing)
thing.replace(/'/g, '"')
// this is to remove the apostrophes from the outside of the object. I thought that would change things before. it does not. still outputs a single {
JSON.parse(thing)
console.log(thing[0])
instead of getting a big huge string that I need or whatever is written in extension_id. I get a {. that's it. I think that is because the whole object starts with a curly bracket. this is confirmed to me because console.log(thing[2]) prints e. so what's going on? jsonlint says this is a valid json object but maybe it's just a big string and I should be doing some kind of split to grab whaat's between the first : and the first ,. I'm really not sure.
For two reasons:
object[0] doesn't return the value an object's "first property", it returns the value of the property with the name "0", if any (there probably isn't in your object); and
Because it's JSON, and when you're dealing with JSON in JavaScript code, you are by definition dealing with a string. (More here.) If you want to deal with the object that the JSON describes, parse it.
Here's an example of parsing it and getting the value of the extension_id property from it:
const parsed = JSON.parse(frames[1]._name);
console.log(parsed.extension_id); // The ID

Converting stream to string in node.js

I am reading a file which comes in as an attachment like follows
let content = fs.readFileSync(attachmentNames[index], {encoding: 'utf8'});
When I inspect content, it looks ok, I see file contents but when I try to assign it to some other variable
attachmentXML = builder.create('ATTACHMENT','','',{headless:true})
.ele('FILECONTENT',content).up()
I get the following error
Error: Invalid character in string: PK
There are a couple of rectangular boxes (special characters) after PK in the above message which are not getting displayed.
builder here refers to an instance of the xmlbuilder https://www.npmjs.com/package/xmlbuilder node module.
I fixed this by enclosing the string inside a JS escape() method

nodejs skipping single quote from json key in output

I see a very weird problem when json when used in nodejs, it is skipping single quote from revision key . I want to pass this json as input to node request module and since single quote is missing from 'revision' key so it is not taking as valid json input. Could someone help how to retain it so that I can use it. I have tried multiple attempts but not able to get it correct.
What did I try ?
console.log(jsondata)
jsondata = {
'splits': {
'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
'revision': 'master'
}
}
Expected :-
{ splits:
{ 'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
'revision': 'master'
}
}
But in actual output single quote is missing from revision key :-
{ splits:
{ 'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
revision: 'master'
}
}
Run 2 :- Tried below code this also produce same thing.
data = JSON.stringify(jsondata)
result = JSON.parse(data)
console.log(result)
Run 3:- Used another way to achieve it
jsondata = {}
temp = {}
splits = []
temp['revision'] = 'master',
temp['os-name'] = 'ubuntu'
temp['platform-version'] = 'os'
temp['traffic-percent'] = 100
splits.push(temp)
jsondata['splits'] = splits
console.log(jsondata)
Run 4: tries replacing single quotes to double quotes
Run 5 : Change the order of revision line
This is what is supposed to happen. The quotes are kept only if the object key it’s not a valid JavaScript identifier. In your example, the 'splits' & 'revision' don't have a dash in their name, so they are the only ones with the quotes removed.
You shouldn't receive any error using this object - if you do, update this post mentioning the scenario and the error.
You should note that JSON and JavaScript are not the same things.
JSON is a format where all keys and values are surrounded by double quotes ("key" and "value"). A JSON string is produced by JSON.stringify, and is required by JSON.parse.
A JavaScript object has very similar syntax to the JSON file format, but is more flexible - the values can be surrounded by double quotes or single quotes, and the keys can have no quotes at all as long as they are valid JavaScript identifiers. If the keys have spaces, dashes, or other non-valid characters, then they need to be surrounded by single quotes or double quotes.
If you need your string to be valid JSON, generate it with JSON.stringify. If it's OK for it to be just valid JavaScript, then it's already fine - it does not matter whether the quotes are there or not.
If, for some reason, you need some imaginary third option (perhaps you are interacting with an API where someone has written their own custom string parser, and they are demanding that all keys are surrounded by single quotes?) you will probably need to write your own little string generator.

Converting a string into an array in Typescript?

I'm using Angular 4 and a Spring service that I throws an exception with the message being the toString of a List of messages. The problem is that when I receive the exception response and extract the message, instead of being treated like an Array of strings, it's treated as a single string in the format of: "[message 1, message 2]"
Is there a way in typescript to easily convert this String into an array of strings? I tried instantiating a new Array with the string like: new Array(errorResponse.error.message); but that didn't really work.
It should working for you:
var messages = message.substring(1, message.length-1).split(", ");
Fiddle with a function, which doing this is available here.
It works with JSON.Parse("[message 1, message 2]");

How to print JSON element having comma in key?

Here, I have a JSON object like
var Obj = { id: 'xx', 'xlink:href': 'http://www.example.com' }
Now, I can print id by
console.log(Obj.id);
But I am not able to get url by doing like this,
console.log(Obj.xlink:href);
It gives me error like,
SyntaxError: missing ) after argument list
Question is here, How can I print data of a key, having comma in between?
Use bracket notation
Obj["xlink:href"]
More info here
The dot notation in JavaScript is only useful when the key is suitable as a token.
Otherwise, you should use the bracket notation.
Here, Obj['xlink:href'] will return the value you want.
As others have said in their answer, you should try following
console.log(Obj['xlink:href']);

Resources