I am trying to use the POST method to insert some data from a person with JSON. I am using the code from JS to construct, but when i start the transformation, it sends me "ERROR: invalid character ' ' in literal true (expecting 'e')". Does anyone know how to solve it?
const obj = {
"num_matricula": num_matricula,
"limit_date": "2022-05-20",
"admission_date": admission_date,
"cost_center": cost_center,
"pos_number": pos_number,
"role": role,
"department": department,
"pagamento": {
"vinculo": vinculo,
"valor": valor,
"recorrencia": recorrencia,
"contaBancaria": {
"banco": "001",
"carta": "c9160763-db6c-4e8c-a1ad-ad8709c99be2"
}
},
"deficiencia": deficiencia,
"jornada": jornada,
"profile": {
"name": name,
"email": email,
"mobile": mobile
},
"exame": {
"clinica": "6dc84ce4-7d9f-48ec-b9b1-a8a895a21fd4",
"data": "2022-05-15",
"hora": "14:00",
"obs": "Comparecer de manhã",
"guia": "e37dab24-c7a4-4b92-b9d1-32ed538b8300",
},
"docs": ["c9e26093-5e0c-4bd2-bea3-ac5182a6179f"],
"send_sms": true,
"send_email": true
};
const myJSON = JSON.stringify(obj);
Some columns are already provided with data from previous step (you can see in the images below), that is why i just repeated the column name in the JS code. Just to let you know, the boolean types of data are the columns: send_email, send_sms and deficiencia.
The problem is that JSON is a string. So in your first line you see this is not valid json: "num_matricula": num_matricula,
only numbers can be without double quotes: "num_matricula": 1234,
Related
Using moment in Prerequest:
var yesterday = moment().subtract(1, 'days').format("yyyy-MM-DD");
console.log(yesterday);
var pastDate = yesterday;
pm.environment.set("pastDate", yesterday)
Request Body:
"AccountId": 1,
"StartDate": {{pastDate}}
Response:
{
"errors": {
"StartDate": [
"Unexpected character encountered while parsing value: 2. Path 'StartDate', line 7, position 18.",
"Input string '022-06-26' is not a valid number. Path 'StartDate', line 7, position 27."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
}
However when looking at the value in the Enviroment:
pastDate: 2022-06-26
So it seems the first character of the variable is being stripped? Not sure how to address this.
The resolution I found was to put the var inside quotes, as JSON needs to recieve dates inside Quote in order to manipulate the value.
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
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.
I am using Apollo-Server and trying to create a REST query against the IEX REST API which returns back data that looks like this:
{
"symbol": "AAPL",
"companyName": "Apple Inc.",
"exchange": "Nasdaq Global Select",
"industry": "Computer Hardware",
"website": "http://www.apple.com",
"description": "Apple Inc is an American multinational technology company. It designs, manufactures, and markets mobile communication and media devices, personal computers, and portable digital music players.",
"CEO": "Timothy D. Cook",
"issueType": "cs",
"sector": "Technology",
"tags": [
"Technology",
"Consumer Electronics",
"Computer Hardware"
]
}
I am using datasources. My typeDefs and resolvers look something like this:
const typeDefs = gql`
type Query{
stock(symbol:String): Stock
}
type Stock {
companyName: String
exchange: String
industry: String
tags: String!
}
`;
const resolvers = {
Query:{
stock: async(root, {symbol}, {dataSources}) =>{
return dataSources.myApi.getSomeData(symbol)
}
}
};
The Datasource file looks like this:
class MyApiextends RESTDataSource{
constructor(){
super();
this.baseURL = 'https://api.iextrading.com/1.0';
}
async getSomeData(symbol){
return this.get(`/stock/${symbol}/company`)
}
}
module.exports = MyApi
I can run a query and get data back, but it is not formatting in an array and is throwing an error when I run a query like so:
query{
stock(symbol:"aapl"){
tags
}
}
Error:
{
"data": {
"stock": null
},
"errors": [
{
"message": "String cannot represent value: [\"Technology\", \"Consumer Electronics\", \"Computer Hardware\"]",
"locations": [
{
"line": 3,
"column": 5
}
],
"path": [
"stock",
"tags"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"TypeError: String cannot represent value: [\"Technology\", \"Consumer Electronics\", \"Computer Hardware\"]",
The data I am expecting (technology, consumer electronics, and computer hardware) are correct, but not returning in an array. I tried to make a new type for tags, and set the it with a tag property, but the value just returns null.
I am very new to graphql, so any feedback is appreciated!
Inside your type definition for Stock, you're defining the type for the tags field as String!:
tags: String!
That tells GraphQL to expect a String value that will not be null. The actual data being returned by the REST endpoint, however, is not a String -- it's an array of Strings. So your definition should minimally look like this:
tags: [String]
If you want GraphQL to throw if the tags value is null, add an exclamation point to the end to make it non-nullable:
tags: [String]!
If you want GraphQL to throw if any of the values inside the array are null, add an exclamation point inside the brackets. You can also combine the two:
tags: [String!]!
I have a json object that I'm loading from wordpress using the JSON API plugin. When I load the json object and try to log out the parts of it, it seems like it treats every single character as its own object so the loop returns me a couple thousand objects all with item in it which is a single character. This is my first time using json so idk if i'm missing a step here. this is the code I'm using so far.
function getProjInfo(theId){
$.ajax({// calling the ajax object of jquery
type: "GET",// we are going to be getting info from this data source
url: 'http://testing.charter21.com/api/get_post/?post_id='+ theId,//the datasource
dataType: "application/json",
success: function(data){
parseJson(data);
}, // what happens when it is successful at loading the XML
error: function(){
alert("error");
}
});
}//end of the function
function parseJson(inData){
postInfo = inData;
$.each(postInfo, function(index, value){
console.log(this);
});
}
the json looks like this:
{
"status": "ok",
"count": 10,
"count_total": 19,
"pages": 2,
"posts": [
{
"id": 175,
"type": "post",
"slug": "home-page-slider",
"url": "http:\/\/testing.charter21.com\/uncategorized\/home-page-slider\/",
"status": "publish",
"title": "Home Page slider",
"title_plain": "Home Page slider",
"content": "<p>The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.<\/p>\n",
"excerpt": "The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.",
"date": "2011-01-25 10:40:25",
"modified": "2011-01-25 10:40:25",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"attachments": [],
"comment_count": 0,
"comment_status": "open"
}
so basically instead of giving me "status" as an key and "ok" as a value, i get "s" as an object with an index 0 that has a value of "s" for every single character in the json object. Any help on this matter would be appreciated.
You need to set dataType:json in your $.ajax() request so that jQuery converts the JSON-formatted string into a JavaScript object for you to process as such. You're currently using application/json which is a mime type, and not a valid value for this field in a jQuery request.
In your case you can even try data = eval(data) , this javascript statement should convert your string to json object.
Use the Jquery function:
data = $.parseJSON(data);
before using $.each.
The way I solved it in my AngularJS app is by sending the response from the server (I'm using Node Express) as a JavaScript object, rather than as a string. Nothing else worked for me.
var response = {};
response.error = "Error message";
res.send(response);