How to parse JSON with escaped doublequotes, using node.js? - node.js

Here is an example of some JSON I am working with:
{"name":"John","attributes":"{\"key\":\"value\"}"}
Here it is again, in a more readable format:
{
"name": "John",
"attributes": "{\"key\":\"value\"}"
}
Notice above that the doublequotes surrounding key and value are escaped. That's necessary, and is valid JSON (checked at jsonlint.com).
I am trying to get the value of "name", but the escaped doublequotes are causing an error.
What am I doing wrong in my node.js code?
var theString = '{"name":"John","attributes":"{\"key\":\"value\"}"}';
var theJSON = JSON.parse(theString);
var theName = theJSON.name;
console.log("name = " + theName);
Below is the output. The error occurs on the 2nd line of my code, where I "JSON.parse()" the string. JSON.parse seems to be removing the backslashes, turning valid JSON into invalid JSON.
undefined:1
{"name":"John","attributes":"{"key":"value"}"}
^
SyntaxError: Unexpected token k in JSON at position 31

Since that part of the data is JSON-within-JSON, you'd parse the JSON, then parse the JSON on the attributes property:
const obj = JSON.parse(json);
obj.attributes = JSON.parse(obj.attributes);
Live Example:
const json = document.getElementById("json").textContent;
const obj = JSON.parse(json);
obj.attributes = JSON.parse(obj.attributes);
console.log(obj);
<pre id="json">{
"name": "John",
"attributes": "{\"key\":\"value\"}"
}</pre>

Related

How to use numbers in the JSON path with node.js?

I have this JSON file: (EDITED)
{
"user": {
"S-1-5-21-2659826518-2396530539-1407762326-1001": {
"username":"xyz",
"password":"xyz#123",
"email":"xyz#xyz.com",
"uid": 1100
},
"S-1-5-21-2659826518-2396530539-1407762326-1002": {
"username":"abc",
"password":"abc#456",
"email":"abc#abc.de",
"uid": 2222
}
}
}
(the JSON file is valid)
and I need to get the values out of it. But when I try to parse the JSON file an error appears:
console.log(jsonContent.S-1-5-21-2659826518-2396530539-1407762326-1001.username);
^^^^^
SyntaxError: Invalid or unexpected token
also, the username is underlined red from my syntax highlighter. (so there is something wrong)
So I searched the internet and found nothing about it.
Here is my code:
const fs = require('fs');
const filename = "C:/Users/Jonas/Documents/Visual_Studio_Code/Node.js/json.json"
contents = fs.readFileSync(filename);
jsonContent = JSON.parse(contents);
console.log(jsonContent.S-1-5-21-2659826518-2396530539-1407762326-1001.username);
For the case I need it, I cant edit the problematic part S-1-5-21-2659826518-2396530539-1407762326-1001.
I also tried to set it like this: console.log(jsonContent."S-1-5-21-2659826518-2396530539-1407762326-1001".username); but that's ever wronger.
For any more information please ask.
You need to use the square bracket notation because the property name has hyphens in it which JavaScipt interprets as the minus (-) operator:
jsonContent['S-1-5-21-2659826518-2396530539-1407762326-1001'].username;
Snippet:
const jsonContent = {
"S-1-5-21-2659826518-2396530539-1407762326-1001": {
"username":"xyz",
"password":"xyz#123",
"email":"xyz#xyz.com",
"uid": 1100
},
"S-1-5-21-2659826518-2396530539-1407762326-1002": {
"username":"abc",
"password":"abc#456",
"email":"abc#abc.de",
"uid": 2222
}
}
const name = jsonContent['S-1-5-21-2659826518-2396530539-1407762326-1001'].username;
console.log(name);

Cannot access json values after converting from xml using xml-js parser

I parse the xml using the following code
var convert = require('xml-js');
var xml = require('fs').readFileSync('./2B2DE7DD-FD11-4F2C-AF0D-A244E5977CBA.xml', 'utf8');
result = convert.xml2json(xml, { spaces: 4});
The result throws the following JSON
{
"declaration": {
"attributes": {
"version": "1.0",
"encoding": "utf-8"
}
}
}
However if i try accesing "declaration" using result["declaration"]the console returns undefined
Should i use another parser or is there something wrong with getting the value.
Please use xml2js instead of xml2json if you want it return object.
result = convert.xml2js(xml, options); // to convert xml text to javascript object
result = convert.xml2json(xml, options); // to convert xml text to json text
The data type of result is String, not JavaScript object. That is, the convert.xml2json(xml, { spaces: 4}); statement will return a JSON String, not JS object.
To access declaration, you need to parse the JSON string to object:
var convert = require('xml-js');
var xml = require('fs').readFileSync('./2B2DE7DD-FD11-4F2C-AF0D-A244E5977CBA.xml', 'utf8');
result = convert.xml2json(xml, { spaces: 4});
result = JSON.parse(result);

Convert the object into a string and bring in the necessary form

An object comes to me. I write the variable key and the value through the loop:
let update_info = [];
for (let[key, value] of Object.entries(req.body)) {
update_info.push(`${key} = ${value}`);
}
console.log(JSON.parse(update_info));
Output to console:
undefined:1
user_name = name,user_email = #email.com,user_password = 12345678,about = aboutaboutaboutabout
^
SyntaxError: Unexpected token u in JSON at position 0
Why it happens?
I need to be displayed in the console like this:
'user_name' = 'name','user_email' = '#email.com','user_password' = '12345678','about' = 'aboutaboutaboutabout
How do i implement this?
I've reproduced your code like this and all you need to do is
JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string.
JSON.parse turns a string of JSON text into a JavaScript object.
let obj = {
"welcome": "hello",
"reply": "hi"
}
let update_info = [];
for (let[key, value] of Object.entries(obj)) {
update_info.push(`${key} = ${value}`);
}
console.log(JSON.stringify(update_info));
Try the below code:
You need not to parse it using JSON.parse because the array is not yet stringified, so you should use toString() to achieve the desired result
let update_info = [];
for (let[key, value] of Object.entries(req.body)) {
update_info.push(`'${key}' = '${value}'`);
}
console.log(update_info.toString());
If you are interested in printing the Object key value pair in the console to have better view use
console.log(JSON.stringify(object, undefined, 2))
This will print the object in proper format indented by 2 spaces

Unexpected token : in JSON at position 603069

I receive the below object in my service but when I am parsing this object I get the error
SyntaxError: Unexpected token : in JSON at position 603069
Code:
var data1 = [];
// Process a chunk of data. This may be called multiple times.
req
.on("data", function(chunk) {
// Append to buffer
data1.push(chunk);
})
.on("end", function() {
var buffer = Buffer.concat(data1);
console.info("Buffer Data Request Body: " + buffer);
buffer = buffer.toString("utf8");
var partsOfStr = buffer.split("&");
//This line gives error
var obj = JSON.parse(
decodeURI(buffer.replace(/&/g, '","').replace(/=/g, '":"'))
);
Object:
{
"type" : "NewThreadVoice",
"incidentId": "398115",
"channel" : "Mobile",
"data": a huge base 64 string
"fileName": "1.aac",
"contentType" : "aac",
"contactId" : "954344"
}
When I reduce the base64 (value of data) to half it works.
A base64 string is not necessary to contain only one "=" character. This character is used for padding (for more information see Why does a base64 encoded string have an = sign at the end )
For example, the codification of home in base64 is aG9tZQ==. Using your code ( .replace(/=/g, '":"') ), this will be transformed into aG9tZQ":"":"
You should use .replace(/=+/g, '":"') for replacing all consecutive = chars.

JSON encode in Slim framework

I am having problems sending a JSON encoded array to my view.
So I am doing this in my route
$data['values'] = array('name'=>'John');
$data['values'] = json_encode($data['values']);
return $this->view->render($res, 'githubpresentation.html', $data);
And in my view, in the script tag I do this
var values = "{{values}}" ;
console.log(values);
values = JSON.parse(values);
console.log(values);
The first console.log, before the JSON.parse outputs this:
{"name":"John"}
And when I do the JSON.parse I get an error, of course
Unexpected token & in JSON at position 1
Now I could do some sort of replace of the &quot, but do I really need to? Shouldn't I be able to send a JSON from the server?
This is related to the default escaping strategy. You can fix it by using the js one:
var values = "{{values|e('js')}}" ;
console.log(values);
values = JSON.parse(values);
console.log(values);
Output:
{"name":"John"}
Object {name: "John"}

Resources