How to get out of this parse error in json? - javascript

var bio = {
"name": "Belphy Baby",
"role": "student",
"contacts": {
"mobile": "9567166100",
"email": "belphy16#gmail.com",
"github": "belphy16",
"location": "kottayam"
},
"welcome message": "and miles to go before i sleep",
"skills": ["leadership", "enthusiastic", "learning"],
"bioPic": "images/fry.jpg"
}
$("#main").append(bio);
Results in error:
Parse error on line 1:
var bio = { "name":
^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

Input should be just a JSON at JSONLint.com
{
"name": "Belphy Baby",
"role": "student",
"contacts": {
"mobile": "9567166100",
"email": "belphy16#gmail.com",
"github": "belphy16",
"location": "kottayam"
},
"welcome message": "and miles to go before i sleep",
"skills": ["leadership", "enthusiastic", "learning"],
"bioPic": "images/fry.jpg"
}
EDIT:
Answer is based on OP's first revision. Note the image he provided.
The error he's getting is coming from the misuse of the site's JSON validation service.
As the service's name suggests, it validates a JSON file's syntax.
Our OP's code contains hints of JavaScript. If inputted at JSONLint, it will give us his error; stating that the should-be JSON input has an error.

Related

HMAC-SHA256 in Python is producing different output to Nodejs

I have a python script which uses the HMAC-hashlib.sha256 algorithm to generate a signature to authenticate over API.
# ZenEmu
import base64
import hashlib
import hmac
import json
from datetime import datetime
import requests
data = json.dumps(
{
"version": "1",
"id": "284512",
"created": "2023-01-17T02:26:29Z",
"updated": "2023-01-17T02:26:29Z",
"url": "https://hitchhikerio.zendesk.com/agent/tickets/284512",
"type": "Question",
"status": "Closed",
"priority": "Low",
"title": "[TEST4] Please Ignore!",
"description": "first comment",
"tags": "test",
"requester_email": "cedric.damian#gmail.com",
"assignee_email": "admin.castle#gmail.com",
"latest_comment": {
"id": "6586310212693",
"is_public": "true",
"author_email": "admin.castle#gmail.com",
"body": "second reply!",
},
}
).encode('utf-8')
sig = base64.b64encode(
hmac.new(
"secret".encode("utf-8"),
"2022-10-10T04:42:00Z".encode("utf-8") + data,
hashlib.sha256,
).digest()
)
print(sig)
This python file pirnts this result as the signature (sig) = b'DJXG/w1ARbM2ZOQ3pamMEkNY7qSJXpjbQMsARyWCr0Y='
I have tried converting this to Javascript with the help of my colleagues and referring to similar questions and resources online to no avail
This is my Javascript file
const crypto = require('crypto');
const utf8 = require('utf8')
const data = utf8.encode(JSON.stringify({
version: "1",
id: "284512",
created: "2023-01-17T02:26:29Z",
updated: "2023-01-17T02:26:29Z",
url: "https://hitchhikerio.zendesk.com/agent/tickets/284512",
type: "Question",
status: "Closed",
priority: "Low",
title: "[TEST4] Please Ignore!",
description: "first comment",
tags: "test",
requester_email: "cedric.muuo#tradecore.com",
assignee_email: "admin.castle#tradecore.com",
latest_comment: {
id: "6586310212693",
is_public: "true",
author_email: "admin.castle#tradecore.com",
body: "second reply!",
},
}));
console.log(data);
const sig = crypto
.createHmac('sha256', utf8.encode('secret'))
.update(utf8.encode("2022-10-10T04:42:00Z") + data)
.digest('base64')
console.log(sig);
which prints the output Yqi7WvMPxdSlo5Vb9YlcbX2zu5aQpungXhuCYx3bc+4=
How do I get the Javascript code to generate the same output as the python script? (b'DJXG/w1ARbM2ZOQ3pamMEkNY7qSJXpjbQMsARyWCr0Y=')
EDIT: THE PYTHON FILE SHOULD STAY UNCHANGED, IT PRODUCES THE CORRECT OUTPUT.
Your JSON strings aren't identical. Python outputs the following:
'{"version": "1", "id": "284512", "created": "2023-01-17T02:26:29Z", "updated": "2023-01-17T02:26:29Z", "url": "https://hitchhikerio.zendesk.com/agent/tickets/284512", "type": "Question", "status": "Closed", "priority": "Low", "title": "[TEST4] Please Ignore!", "description": "first comment", "tags": "test", "requester_email": "cedric.damian#gmail.com", "assignee_email": "admin.castle#gmail.com", "latest_comment": {"id": "6586310212693", "is_public": "true", "author_email": "admin.castle#gmail.com", "body": "second reply!"}}'
Node outputs the following:
'{"version":"1","id":"284512","created":"2023-01-17T02:26:29Z","updated":"2023-01-17T02:26:29Z","url":"https://hitchhikerio.zendesk.com/agent/tickets/284512","type":"Question","status":"Closed","priority":"Low","title":"[TEST4] Please Ignore!","description":"first comment","tags":"test","requester_email":"cedric.muuo#tradecore.com","assignee_email":"admin.castle#tradecore.com","latest_comment":{"id":"6586310212693","is_public":"true","author_email":"admin.castle#tradecore.com","body":"second reply!"}}'
Notice how the Node version has no whitespace.
EDIT:
To fix it, you can use the Python function as follows:
json.dumps(your_data_object_here, separators=(",",":"))
Edit again:
To insert spaces into the Node version you can try the following:
JSON.stringify(obj).replace(/("[^"]+"[:,])/g, "$1 ");
That should insert spaces after all the : and ,, like in Python. Note that it does not handle escaped quote marks inside the strings. You'll need to update the Regex to deal with that.
Final edit:
Here's an alternate JS approach:
const data = JSON.stringify(obj, null, 1).match(/(\S.*)/gm).join("");
This constructs a "pretty-printed" JSON string with newlines and everything, then grabs each line starting at the first non-whitespace and joins them all up. That strips newlines and indentation, but preserves all whitespace between separators and inside strings. Should be sufficient.

split a string message into array in Typescript

I'm trying to split a string message into array in Typescript. I cannot use comma as there's a json string. I tried to parse but I'm getting an error.
const msgs = 'string_no_quotes,"string-with#}-weirdchars",{"ckey":null,"email":"user#gmail.com","pass":"password","name":{"firstName":"User","middleName":"","lastName":"Name"},"address":{"street": "test street", "country":"some country", "zip": "639821"},"status":1},opt-data'
const messages:string[] = JSON.parse(msgs.toString())
The error :
SyntaxError: Unexpected token c in JSON at position 1
at JSON.parse (<anonymous>)
What could be a best solution to get values in to string array.
PS: If you wonder why I came up with such nasty string, its 'ZeroMQ' message. And, i tried,
JSON.parse("["+msgs.toString()+"]")
eval("("+msgs.toString()+")")
Got it figured out with a custom func after a long tryout, not a straight forward, but works as needed. The original problem was the input is received as a buffer from zmq broker and there's that weird format of data from msg.toString()
Steps:
Used a regex to segregate the object data,
replace the regex match with template string,
split it, replace the 'made' array and return it.
export const parseTheCrapOutOfThatDamnString = (paramString: string) => {
const regEx = RegExp("(?<={)(.*)(?=})") //(?<={)(.*)(?=}) //https://regexr.com/2tr5t
if(regEx.test(paramString)) {
var theMatch:string = `${_.head(paramString.match(regEx))}` || "" //;console.log(`\n${theMatch}\n`)
var paramsArray = _.replace(paramString, theMatch, "replaceable").split(',') //;console.log(paramString)
paramsArray[paramsArray.indexOf('{replaceable}')] = JSON.parse(`{${theMatch}}`)
return paramsArray;
}else {
return JSON.parse("["+paramString+"]")
}
}
the call,
const msgs = 'string_no_quotes,"string-with#}-weirdchars",{"ckey":null,"email":"user#gmail.com","pass":"password","name":{"firstName":"User","middleName":"","lastName":"Name"},"address":{"street": "test street", "country":"some country", "zip": "639821"},"status":1},opt-data'
console.log(parseTheCrapOutOfThatDamnString(msgs))
the final output:
["string_no_quotes", "string-with#}-weirdchars", {
"ckey": null,
"email": "user#gmail.com",
"pass": "password",
"name": {
"firstName": "User",
"middleName": "",
"lastName": "Name"
},
"address": {
"street": "test street",
"country": "some country",
"zip": "639821"
},
"status": 1
}, "opt-data"]
here it is Typescript play

How to create a query using typeorm query builder to filder data from the database?

I am just new to typeorm , I am using nodejs/nestjs , I am trying to create a query where in data from the database which is the course could be filter by instructor which is the firstname and lastname , filter by course_name and filter courses by subject. I tried using 'where' and 'orWhere' but cant seem to wrap things up, Anyone can give an advice of a better implementation ? Thank you. Much appreciated.
The query below is working , I am having trouble with the "where" condition
Code
async findAll(options: IPaginationOptions, query): Promise<Pagination<CourseEntity>> {
console.log('query :', query);
const courses = await getRepository(CourseEntity)
.createQueryBuilder('course')
.leftJoinAndSelect('course.user', 'user')
.leftJoinAndSelect('course.subject', 'subject')
// eslint-disable-next-line #typescript-eslint/camelcase
.where('course.course_name = :course_name', { course_name: query.course_name });
return paginate<CourseEntity>(courses, options);
}
here is the query param
query : { limit: '10', firstname: 'mark', lastname: 'gunn' , course_name: 'Comscie'}
Sample data from the database
{
"id": 4,
"course_name": "BS-IT",
"description": "BS-IT DBMS",
"created": "2020-03-19T16:40:46.000Z",
"updated": "2020-03-19T16:40:46.000Z",
"user": {
"id": 20,
"firstname": "Mark",
"lastname": "Gunn",
"role": "Instructor",
"email": "mark#gmail.com",
"isActive": false,
"created": "2020-03-19T16:06:21.000Z",
"updated": "2020-03-19T16:06:34.000Z"
},
"subject": {
"id": 2,
"subject_name": "IT 100",
"description": "Fundamandetals",
"created": "2020-03-18T03:58:34.000Z",
"updated": "2020-03-18T03:58:34.000Z"
}
}
It looks good. Just add other conditions with andWhere
For my project with Typeorm, I prefer use the Find Option Object (https://typeorm.io/#/find-options), because it's easier to generate request from an object but you can't do some advanced join (but in your case it's totally ok)
They are not better implementation just multiple solutions.

How do I access "order" in this JSON (with semicolons in the name)?

Vijay Anand asked this question yesterday, but it was closed before he got an answer:
HTTP Response:
{
"entry": {
"#xml:base": "https://API_PROC_SRV/",
"#xmlns": "http://www.w3.org/2005/Atom",
"#xmlns:m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
"#xmlns:d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
"id": "https://API_PROC_SRV/A_Order",
"title": {
"#type": "text",
"#text": "A_Order()"
},
"updated": "2020-02-29T07:33:28Z",
"category": {
"#term": "Type",
"#scheme": "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"
},
"link": [],
"content": {
"#type": "application/xml",
"m:properties": {
"d:Order": "123456789"
}
}
}
}
Javascript code:
var json = response;
var order = json.object.entry.content['m:properties']['d:Order']; // I intend to read Order no from the below response.
Error (example, jsbin.com):
"TypeError: Cannot read property 'entry' of undefined
at null.js:27:25
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"
Per JSLint, the response is valid JSON.
json.object.entry is obviously wrong ... but
Q: What is the correct Javascript syntax to access the "order" value (named d:Order), when m:properties and d:Order both have semicolons in the name?
PS: I nominated Vijay's original question for re-opening ... but I'm not optimistic. Hence my new question.
You need to parse the JSON. And there's no object property anywhere, it's jut json.entry.content.
response = `{
"entry": {
"#xml:base": "https://API_PROC_SRV/",
"#xmlns": "http://www.w3.org/2005/Atom",
"#xmlns:m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
"#xmlns:d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
"id": "https://API_PROC_SRV/A_Order",
"title": {
"#type": "text",
"#text": "A_Order()"
},
"updated": "2020-02-29T07:33:28Z",
"category": {
"#term": "Type",
"#scheme": "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"
},
"link": [],
"content": {
"#type": "application/xml",
"m:properties": {
"d:Order": "123456789"
}
}
}
}`;
var json = JSON.parse(response);
var order = json.entry.content['m:properties']['d:Order'];
console.log(order);

JSON Lint validated JSON String but the same doesnt gets parsed with JS

I have built a Automation Test Framework using TestNG + Selenium where I am generating a HTML Report at the end of the execution.
I am passing the execution details directly as JSON string (as we are not hosting the report into a webserver, this is a local setup) within the HTML file and running an internal JS to populated the data into the report grid.
Everything is working fine, except that once I get an exception I am trying to report the stacktrace in HTML which again gets into the report as a JSON value and JS denies to parse it.
To the understand the problem better, please check the code snippet below
// This is where I am reporting the exception
public static void ReportException(Exception e){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
BuildReport(itrStepCnt,"Exception Occurred!",StringEscapeUtils.escapeJson("Exception Details - "+sw.toString()),"ERROR",captureScreenshot());
ItrConcludeReport();
}
and the converting a map to JSON String and finally reporting to HTML
content = content.replaceAll("#testrepdt#",finalContent);
JS is trying to parse it as following and fails to do the samr
var jsondata = JSON.parse(dt);
Here is the JSON String which gets validated with Lint but didnt gets passed through JSON Parser
[
{
"testclasspath": "app.applicationa.testcases.module1",
"testcasename": "TC004",
"executiontime": "5799ms",
"teststatus": "PASS",
"iteration": [
{
"teststeps": [
{
"Status": "PASS",
"Description": "pass desc",
"StepNo": "1",
"StepName": "StepName 1:1",
"Snapshot": "./SNAPSHOTS/15_Nov_2015_020306095_73350.png"
}
],
"itrname": "Iteration: 1"
},
{
"teststeps": [
{
"Status": "PASS",
"Description": "pass desc",
"StepNo": "1",
"StepName": "StepName 1:2",
"Snapshot": "./SNAPSHOTS/15_Nov_2015_020306291_46233.png"
}
],
"itrname": "Iteration: 2"
},
{
"teststeps": [
{
"Status": "PASS",
"Description": "pass desc",
"StepNo": "1",
"StepName": "StepName 1:3",
"Snapshot": "./SNAPSHOTS/15_Nov_2015_020306481_36460.png"
}
],
"itrname": "Iteration: 3"
}
]
},
{
"testclasspath": "app.applicationa.testcases.module1",
"testcasename": "TC002",
"executiontime": "6025ms",
"teststatus": "PASS",
"iteration": [
{
"teststeps": [
{
"Status": "PASS",
"Description": "pass desc",
"StepNo": "1",
"StepName": "StepName 1:3",
"Snapshot": "Not Required"
},
{
"Status": "ERROR",
"Description": "Exception Details - java.lang.NullPointerException\\r\\n\\tat app.applicationa.testcases.module1.TC002(module1.java:64)\\r\\n\\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\\r\\n\\tat sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)\\r\\n\\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)\\r\\n\\tat java.lang.reflect.Method.invoke(Unknown Source)\\r\\n\\tat org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)\\r\\n\\tat org.testng.internal.Invoker.invokeMethod(Invoker.java:639)\\r\\n\\tat org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)\\r\\n\\tat org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)\\r\\n\\tat org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)\\r\\n\\tat org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)\\r\\n\\tat org.testng.TestRunner.privateRun(TestRunner.java:774)\\r\\n\\tat org.testng.TestRunner.run(TestRunner.java:624)\\r\\n\\tat org.testng.SuiteRunner.runTest(SuiteRunner.java:359)\\r\\n\\tat org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)\\r\\n\\tat org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)\\r\\n\\tat org.testng.SuiteRunner.run(SuiteRunner.java:261)\\r\\n\\tat org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)\\r\\n\\tat org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)\\r\\n\\tat org.testng.TestNG.runSuitesSequentially(TestNG.java:1191)\\r\\n\\tat org.testng.TestNG.runSuitesLocally(TestNG.java:1116)\\r\\n\\tat org.testng.TestNG.run(TestNG.java:1024)\\r\\n\\tat org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:112)\\r\\n\\tat org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:205)\\r\\n\\tat org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:176)\\r\\n",
"StepNo": "1",
"StepName": "Exception Occurred!",
"Snapshot": "./SNAPSHOTS/null"
}
],
"itrname": "Iteration : 1"
}
]
}
]

Categories

Resources