Array to JSON Array in Swift - ios

I have two array of Integers and I like to send it to my mongodb database. When I send it to database in Alamofire as paramter and in code data_array 1 and 2 refers to Int arrays.
let parameters_post: Parameters = [
"sensor_id": "ecg_raw",
"member_id": "58d3f509e48f4ca90dd218e4",
"esignal": "3.5V",
"ts": "emre",
"value1" : data_array1,
"value2" : data_array2
]
Alamofire.request("https://api.mlab.com/api/1/databases/mysignal/collections/Cecgraw?apiKey=2ABdhQTy1GAWiwfvsKfJyeZVfrHeloQI", method: .post, parameters: parameters_post,encoding: JSONEncoding.default, headers: nil).responseData{ response in
print(response.request)
print(response.response)
print(response.result)
}
However, It is seen as like this in mongodb. I think which is incorrect;
{
"_id": {
"$oid": "58f9d0e7c2ef162ad3000cb6"
},
"sensor_id": "ecg_raw",
"member_id": "58d3f509e48f4ca90dd218e4",
"value2": [
[
240,
279,
555,
547,
504
]
],
"value1": [
[
135,
91,
101,
115,
106
]
],
"esignal": "3.5V",
"ts": "emre"
}

As per you said you want to send value for key value as [(Int, Int)]. But actually you are sending as [[(Int, Int)]], which means array of array of tuples(Hope you need to send as array of tuples).
Try to send list below,
let parameters_post: Parameters = [
"sensor_id": "ecg_raw",
"member_id": "58d3f509e48f4ca90dd218e4",
"esignal": "3.5V",
"ts": "emre",
"value" : data_array
]
Thanks.

Related

Telegraf splits input data into different outputs

I want to write Telegraf config file which will:
Uses openweathermap input or custom http request result
{
"fields": {
...
"humidity": 97,
"temperature": -11.34,
...
},
"name": "weather",
"tags": {...},
"timestamp": 1675786146
}
Splits result on two similar JSONs:
{
"sensorID": "owm",
"timestamp": 1675786146,
"value": 97,
"type": "humidity"
}
and
{
"sensorID": "owm",
"timestamp": 1675786146,
"value": -11.34,
"type": "temperature"
}
Sends this JSONs into MQTT queue
Is it possible or I must create two different configs and make two api calls?
I found next configuration which solves my problem:
[[outputs.mqtt]]
servers = ["${MQTT_URL}", ]
topic_prefix = "owm/data"
data_format = "json"
json_transformation = '{"sensorID":"owm","type":"temperature","value":fields.main_temp,"timestamp":timestamp}'
[[outputs.mqtt]]
servers = ["${MQTT_URL}", ]
topic_prefix = "owm/data"
data_format = "json"
json_transformation = '{"sensorID":"owm","type":"humidity","value":fields.main_humidity,"timestamp":timestamp}'
[[inputs.http]]
urls = [
"https://api.openweathermap.org/data/2.5/weather?lat={$LAT}&lon={$LON}2&appid=${API_KEY}&units=metric"
]
data_format = "json"
Here we:
Retrieve data from OWM in input plugin.
Transform received data structure in needed structure in two different output plugins. We use this language https://jsonata.org/ for this aim.

How can I parse JSON with this structure(multipart file)?

My java spring boot app is sending JSON that includes a multi-part file, which I need to parse(using angular) in order to target 'picture" inside of "fileupload" when GET is called.
Here is the JSON coming to UI when GET is called:
{
"id": 1,
"name": John,
"fileupload": "MemberFile(id=1, fileId=1, fileName="sample.png", picture=[-119, 80, 78, 71, 13,..., -126])"
}
Any help would be greatly appreciated. Let me know if more details are needed. Thanks
Use JSON.parse to parse your string to javascript object.
const json = '{ "id": 1 "name": John "fileupload": "MemberFile(id=1, fileId=1, fileName="sample.png", picture=[-119, 80, 78, 71, 13,..., -126])" }';
const obj = JSON.parse(json);
console.log(obj);
// expected output: true

How to get the value from a List using Rest Assured?

I am trying to grab the first value of courseNumber for studenId=123 using Rest Assured.
When I using
.body("students.courseList.courseNumber[0]",equalTo(1000000000))
I am getting:
Expected: <1000000000>
Actual: [1000000000, 1000000001, 1000000002, 1000000003, ...........]
There are more than 10 courseList for studentId 123.
Also is it possible to use regex to grab a particular element from JSON Response or how do I get the path of an element when I have a few thousand lines of JSON Response.
Sample Response -
{
"students": [
{
"studentId": "ABC",
"studentName": "Abcd Abcd",
"courseDescription": "AAJSHKJASSJAK LASNLKASA KJk;;K K;;KK;K;KL;K;",
"creditRemaining": 100,
"classStartDate": "20191220"
},
{
"studentId": "123",
"studentName": "DEFG, VBNH",
"courseDescription": "AAJSHKJASSJAK LASNLKASA KJk;;K K;;KK;K;KL;K;",
"classSchedule": 2,
"classStartDate": "20191220",
"slotsRemaining": 10,
"courseList": [
{
"courseNumber": 1000000000,
"courseName": "Chemistry",
"courseInstructor": "HGJ IOUIOU"
"courseCity": "New York",
"courseLevel": 100,
"description": "GJKJLKJLafgdhgf ljkllklk klyiyy mnbbnkljlkj
yttiuyuyuyoyo
jhlkjkljkl"},
{
"courseNumber": 1000000001,
"courseName": "History",
"courseInstructor": "HGJ IOUIOU"
"courseCity": "New York",
"courseLevel": 100,
"description": "GJKJLKJLafgdhgf ljkllklk klyiyy mnbbnkljlkj yttiuyuyuyoyo
jhlkjkljkl"},
]
}
students.courseList.courseNumber[0][0] --> will give 1000000000
students.courseList.courseNumber[0][1] --> will give 1000000001

i want to fetch product_description but it contain html so i m getting confuse that how to get proper format from it

JSON:
{ "wishlist": [ { "wishlist": 0 } ], "cart": [ { "cart": 1 } ], "product": [ { "promo_id": 0, "avals": 0, "dis": null, "mp_product_id": 252, "mp_category_id": 113, "product_name": "Pink Soft Net Fabric Kids Angel Lehenga Choli", "product_description": "
This Pink Coloured Traditional Soft Net Fabric Lehenga Choli gives a beautifull look to your child. This Outfit come with Brocket Fabric Lehenga and Top has Soft Net Fabric with Silk Lining come along with Soft Net Dupatta .\r\n\r\n
You can make your kids wear this outfit for parties and functions.\r\n\r\n
Type :\r\n\r\n
*Semi-Stitched*\r\n\r\n
FABRIC :\r\n\r\n
Top : Unstitched Designer Brocade fabric
\r\nBottom : stitched Soft Net fabric
\r\nDupatta : Soft Net fabric
\r\nInner : Silk fabric\r\n\r\n
Size Chart :\r\n\r\n
1 to 5 year : 30 inches
\r\n6 to 8 year : 32 inches
\r\n9 to 10 year : 34 inches
\r\n10 to 15 year: 36 inches\r\n\r\n
Care
\r\nDry Clean\r\n", "sku_number": "Angel_3_Pink", "qty": 25, "likes_count": 0, "list_price": 2082, "selling_price": 1249, "discount": 41 } ], "image": [ { "image_name": "Sweet Angel Vol3-Pink.jpg" } ], "variant": [ { "Color": "PINK", "Size": "S,M,L,XL", "Occasion": "Party" } ], "related": [ { "mp_product_id": 231, "mp_category_id": 113, "product_name": "White Peacock Kids Indo Western ", "product_description": "
This White Coloured Traditional Banglory Top Fabrics Indo Western gives a beautifull look to your child. This Outfit come with Paper Silk Fabric Lehenga and Top has Banglory Fabric.\r\n\r\n
You can make your kids wear this outfit for parties and functions.\r\n\r\n
Type :\r\n\r\n
*Stitched*\r\n\r\n
FABRIC :\r\n\r\n
Top - Banglory (foam seat work),\r\n\r\n
Lehenga - Paper silk,\r\n\r\n
Size Chart :\r\n\r\n
6 to 12 year : 34 inches\r\n\r\n
Care
\r\nDry Clean\r\n", "product_image": "", "seller_product_code": "White_Peacock", "system_product_code": 0, "sku_number": "White_Peacock", "status": "A", "is_features": 0, "list_price": 2271, "selling_price": 1249, "qty": 25, "weight": "700", "cod_charge": "0", "shipping_charge": "0", "likes_count": 0, "create_date": "2017-06-26 12:38:51", "modify_date": "2017-06-26 12:39:37", "main_order": 14, "set_order": 0, "image_name": "Peacock White Kids \u00a0--- CKL 216 --- Rs. 625.jpg" }
Yes you are doing the same thing, but your code is prone to crashes as you are forcefully trying to unwrap optionals. Try this instead
Alamofire.request(APIProductDetail, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
switch response.result {
case .success(let responseResultValue):
if let responseResult = responseResultValue as? [String:Any] {
if let productsList = responseResult["product"] as? [[String:Any]] {
for product in productsList {
if let productDescription = product["product_description"] as? String {
print(productDescription) //Here you will get the product description
}
}
}
}
case .failure(let error):
//handle any error here
print(error.localizedDescription)
}
}

swift - how to parse this JSON object

// Get the #1 app name from iTunes and SwiftyJSON
DataManager.getTopAppsDataFromItunesWithSuccess { (iTunesData) -> Void in
let json = JSON(data: iTunesData)
println(json)
how to access all the elements of["venues"]["pub city"]["venue"] ?
{
"venues":{
"cityuser":"Beirut",
"venue-usernewplace":{
"star":[
],
"idcat":[
],
"namecat":[
],
"name":[
],
"id":[
],
"phone":[
],
"address":[
],
"crossStreet":[
],
"lat":[
],
"lng":[
],
"cc":[
]
},
"placesofpeople":{
"star":"false",
"nameplace":"B0 18",
"idplace":"4b52670df964a520847b27e3",
"count":"4",
"cc":"LB",
"phone":"01580018",
"crossStreet":"Main Highway",
"lat":"33.898404713314",
"lng":"35.534128372291",
"address":"Karantina"
},
"pubcity":{
"venue":[
{
"id":"4fe75b17e4b032d653ce50fd",
"idcat":"4bf58dd8d48988d11e941735",
"name":"Cl\u00e9 Cafe-Lounge Bar",
"phone":"71200712",
"address":"Mohammed Abdel Baki Street, Clemenceau",
"crossStreet":"Hamra, Facing Najjar Hospital",
"lat":"33.897185328966",
"lng":"35.487202808518",
"cc":"LB",
"count":"0",
"namecat":"Cocktail Bar",
"star":"false"
},
{
"id":"4e3e7533fa76455375c56a33",
"idcat":"4bf58dd8d48988d11f941735",
"name":"Skybar",
"phone":"03939191",
"address":"Biel",
"crossStreet":"Downtown Beirut",
"lat":"33.90610643966",
"lng":"35.510663636771",
"cc":"LB",
"count":"0",
"namecat":"Nightclub",
"star":"false"
},
{
"id":"4b52670df964a520847b27e3",
"idcat":"4bf58dd8d48988d11f941735",
"name":"B 018",
"phone":"01580018",
"address":"Karantina",
"crossStreet":"Main Highway",
"lat":"33.898404713314",
"lng":"35.534128372291",
"cc":"LB",
"count":"0",
"namecat":"Nightclub",
"star":"false"
},
There's two methods I know of.
1 Post that wall of text into a JSON formatter which makes that blob more readable. In which case you can then inspect which keys you can pull out from it.
2 Check the documentation.
Using swiftyJson:
if let venues = json["venues"]["pubcity"]["venue"].array {
//venue is an array of the dictionaries.
for venue in venues {
//just printing the name, but you have the whole dictioary of each venue here.
println(venue["name"].string!)
}
}

Resources