RapidJSON on Telegram Data - c++

I am trying to figure out how to extract data from Telegram which is JSON Data. I am using RapidJSON but when i tried the code below, i dont see any data extracted.
JSON
{
"ok":true,
"result":{
"message_id":90,
"from":{
"id":123456854,
"is_bot":true,
"first_name":"TestTGBot",
"username":"TestTGBot"
},
"chat":{
"id":125415667,
"first_name":"Test Account",
"type":"private"
},
"date":1506507292,
"text":"Test Bot Message"
}
}
Code
Document document;
document.Parse(rBuffer.c_str());
for(Value::ConstMemberIterator iter = document.MemberBegin();iter!=document.MemberEnd();++iter)
{
tmp.Format("%s",iter->name.GetString());
MessageBox(tmp);
}
It only returns "ok" and "result" value.

Related

Runner Postman with list

I'm struggling to make my runner works.
Here the raw body of my method
{
"itemList": [
"{{items}}"
],
"storeType": 7,
"storeNum": [
"{{store}}"
]
}
i want to use a csv file containing line like this
store,items
115,"1097456,855591,716027"
The issue is, i don't know how to format the string i got from the file "1097456,855591,716027" to make my body works.
My body should look's like that:
{
"itemList": [1097456,855591,716027],
"storeType": 7,
"storeNum": [115]
}
If i remove the double quote from "{{ITEMS}}" i got a json error.
I'm lost and start to think this is impossible :(
Any help is welcome.
Thanks
Step 1: Change the request body
{
"itemList": {{items}},
"storeType": 7,
"storeNum": {{stores}}
}
Step 2: Write code in Pre-Request tab to convert String to a list of number.
let stores = readInput("store");
let items = readInput("item");
pm.environment.set("stores", JSON.stringify(stores));
pm.environment.set("items", JSON.stringify(items));
function readInput(header){
let input = pm.iterationData.get(header).toString();
let fields = [];
if (input.includes(",")) {
inputs = input.split(",");
fields = inputs.map(x => parseInt(x));
} else {
fields.push(parseInt(input));
}
return fields;
}
CSV file:
Sample request body:

Formatting DynamoDB data to normal JSON in Typescript and AWS Lambda

I am retrieving data from DynamoDB using a query and I get the following returned:
[{"serviceUserId":{"S":"123456789"},"createdDate":{"S":"11-12-2021"}}]
The DynamoDB JSON format has the type in in which I am trying to get rid of by converting to a normal JSON format. I have tried using the AWS.DynamoDB.Converter.unmarshall but I am getting an error in my code:
Argument of type 'ItemList' is not assignable to parameter of type "AttributeMap".
Index signature for type 'string' is missing in type "AttributeMap[]".
Here is my code:
if (result.Count > 0) {
const newImage = AWS.DynamoDB.Converter.unmarshall(
result.Items
)
console.log('new Image: ' + JSON.stringify(newImage));
resolve(newImage);
} else {
console.log('No record found');
reject(err);
}
If I remove the [] brackets in the DynamoDB JSON then it is converted successfully, but obviously I cannot do this in my program as the brackets are there for a reason!
Does anyone know how to convert my JSON file to a format that unmarshall will accept?
Map through the items and unmarshal one by one. (un)marshal accepts an object type, not an array.
import { marshall, unmarshall } from '#aws-sdk/util-dynamodb'; // SDK V3, but worked the same in V2
(() => {
const items = [{ serviceUserId: { S: '123456789' }, createdDate: { S: '11-12-2021' } }];
// from DynamoDB JSON
const unmarshalled = items.map((i) => unmarshall(i));
// make the return trip back to DynamoDB JSON
const marshalled = unmarshalled.map((i) => marshall(i));
})();

How to properly set an API call in QML using XMLHttpRequest

I am building a small weather API as exercise to use QML and properly operate an API call using OpenWeather and you can see there a typical API response.
The problem I am having is that I can't get the API call to work. After setting a minimal example with some cities that you can see below, right next to the city it should appear the symbol of the weather, but it does not happen. The list of the icon can be found here. Source code of the MVE can be found here for completeness.
The error from the compiler: qrc:/main.qml:282: SyntaxError: JSON.parse: Parse error
This is what is happening
This is what is expected
Typical API JSON response can be found both here and below:
{
"coord": {
"lon": -122.08,
"lat": 37.39
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 282.55,
"feels_like": 281.86,
"temp_min": 280.37,
"temp_max": 284.26,
"pressure": 1023,
"humidity": 100
},
"visibility": 16093,
"wind": {
"speed": 1.5,
"deg": 350
},
"clouds": {
"all": 1
},
"dt": 1560350645,
"sys": {
"type": 1,
"id": 5122,
"message": 0.0139,
"country": "US",
"sunrise": 1560343627,
"sunset": 1560396563
},
"timezone": -25200,
"id": 420006353,
"name": "Mountain View",
"cod": 200
}
Below a snippet of code related to the API call:
main.qml
// Create the API getcondition to get JSON data of weather
function getCondition(location, index) {
var res
var url = "api.openweathermap.org/data/2.5/weather?id={city id}&appid={your api key}"
var doc = new XMLHttpRequest()
// parse JSON data and put code result into codeList
doc.onreadystatechange = function() {
if(doc.readyState === XMLHttpRequest.DONE) {
res = doc.responseText
// parse data
var obj = JSON.parse(res) // <-- Error Here
if(typeof(obj) == 'object') {
if(obj.hasOwnProperty('query')) {
var ch = onj.query.results.channel
var item = ch.item
codeList[index] = item.condition["code"]
}
}
}
}
doc.open('GET', url, true)
doc.send()
}
In order to solve this problem I consulted several sources, first of all : official documentation and the related function. I believe it is correctly set, but I added the reference for completeness.
Also I came across this one which explained how to simply apply XMLHttpRequest.
Also I dug more into the problem to find a solution and also consulted this one which also explained how to apply the JSON parsing function. But still something is not correct.
Thanks for pointing in the right direction for solving this problem.
Below the answer to my question. I was not reading properly the JSON file and after console logging the problem the solution is below. code was correct from beginning, only the response needed to be reviewed properly and in great detail being the JSON response a bit confusing:
function getCondition() {
var request = new XMLHttpRequest()
request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=key', true);
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status && request.status === 200) {
console.log("response", request.responseText)
var result = JSON.parse(request.responseText)
} else {
console.log("HTTP:", request.status, request.statusText)
}
}
}
request.send()
}
Hope that helps!
In your code, your url shows this: "api.openweathermap.org/data/2.5/weather?id={city id}&appid={your api key}". You need to replace {city id} and {your api key} with real values.
You can solve it by providing an actual city ID and API key in your request URL

Check for null values in request body using Wiremock

I am trying to setup a wiremock stub that will return a 400 error if any field has a null value in the json payload. Basically to simulate a Bad Request. I've been trying with a regex that matches any lowercase string for the json key but it doesn't seem to like it. I can't find any examples of what I want online so not sure if it's even possible.
My Bad Request body:
{
"cat": null,
"dog": {
"id": 1344
},
"horse": {
"id": 1
},
"fish": 1
}
My Stub:
wireMockServer.stubFor(post(urlEqualTo("/sample-api"))
.withRequestBody(matchingJsonPath("$.^[a-z]*", equalTo(null)))
.willReturn(aResponse()
.withStatus(400)
.withHeader("Content-Type", "application/json")))
In this example I would expect the stub to match "cat" as the value of it is null. This isn't the case. Can anyone tell me what I'm doing wrong?
In the WireMock documentation on Request Matching the section on JSON Path matching. In the source code there is a reference to com.jayway.jsonpath.JsonPath library used. The build.gradle refers to version 2.4.0. The documentation for the Jayway JSON Path library can be found on their Github project page. There is a good, but by no means perfect online evaluator here.
The WireMock documentation only shows support for Regular Expression for the node values in the form of the "matchesJsonPath". In the Jayway documenatation there is an online example: $..book[?(#.author =~ /.*REES/i)]. For this reason the only approach is to name all the nodes that are not allowed to be null.
In the below example mapping all the mentioned nodes will be tested, regardless of their depth (see #id). This mapping will not trigger if all the mentioned nodes are not null, but some unmentioned ones are.
{
"request": {
"urlPattern": "/sample-api",
"method": "GET",
"bodyPatterns" : [ {
"matchesJsonPath" : "$..[?(#.cat == null || #.dog == null || #.horse == null || #.fish == null || #.id == null)]"
} ]
},
"response": {
"status": "400",
"headers": {
"Content-Type": "application/json; charset=utf-8"
},
"jsonBody": {
"message": "some sapi message"
}
}
}
If you weren't aware of all possible keys, you could use a Custom Request Matcher to check if the request body contained any null values, and if so, return your 400 error. I'd recommend creating your own class, something that resembles...
public class BodyNullCheck extends RequestMatcherExtension {
#Override
public MatchResult match(Request request, Parameters parameters) {
JSONParser parser = new JSONParser();
try {
JSONObject body = (JSONObject) parser.parse(request.getBody().toString());
for(Iterator iterator = body.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
if (body.get(key) == null) {
return MatchResult.of(true);
}
}
} catch (ParseException ex) {
ex.printStackTrace();
}
return MatchResult.of(false);
}
}
The above takes the request body and converts it to a JSONObject, and then iterates over all keys in the JSONObject. If any of their values are null, then we will return true. If after iterating over all of them, a null value isn't found, we return false.

how to get data from {} in graphql

I want to get data about user addinfo(bool value).
when i do console.log(data.user), i can get data.user referred to below picture.
if when i do console.log(data.user.user), it shows that user is undefined referred to below picture.
{
user(token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImI3ZTA5YmVhOTAzNzQ3ODQiLCJleHAiOjE1NjM4OTcxNzksIm9yaWdJYXQiOjE1NjM4OTY4Nzl9.QFB58dAvqIC9RBBohN1b3TdR542dBZEcXOG1MSTqAQQ") {
user {
id
addinfo
}
}
}
this code show that
{
"data": {
"user": {
"user": {
"id": "4",
"addinfo": false
}
}
}
}
I can't see the rest of your code, but if the code is fetching your users, there is a time before the request comes back where your user has not been fetched yet. It looks like your screenshot shows this. There is an undefined before the successful object.
You need to ensure that the data has come back first be checking if the data prop is truthy or some other way to check if the promise has completed yet.
ie
if (!data.user) return 'Loading...';
return (
<Switch>
...
In GraphQL I'm getting user info using e.g. below code:
async getUser(id) {
const result = await this.api.query({
query: gql(getUser),
variables: {
id,
},
});
return result.data.getUser || null;
}
I'm invoking it by:
const user = await userService.getUser(id);
and I do have access to user properties.
Maybe you're trying to get user data before they are retrieved and available?