Parse String in Restify - json

For the following JSON file
{
"_id":"1",
"Time":"03:20:22"
}
I want to add hours such that "Time" + 2 = "05:20:22";
Using Restify, I do not know how to parse this JSON into caculatable format because if I do data.Time.split(":"); restify does not recognize this command.
How should I parse Strings like "03:20:11" so that I can add number of hours to it?

You can use following sample code: (Make sure data.Time is a string while you retrieve object from restify. Because split function works only on strings)
x= "03:20:22";
y=x.split(':')
z=int(y[0])+2
y[0]=str(z)
print y

Related

Ballerina json datetime value

i have to index documents to elasticsearch to an index which has a date field mapping and i'm trying to build a json with this date value, but ballerina says this seems not possible.
I thought about storing this date value into an xml and after that to convert it to a json but xml has the same problem (i thought this might be a trick...).
I tried to store it into a string and after that to extract the json payload from that string but it gives me this error:
error: {ballerina/io}GenericError message=unrecognized token 'date=time=1591128342000'
I thought about dealing with this string to date conversion from inside elasticsearch but i would like to keep this scenario as the last one. I don't like it, beacause i have to do some queries based on timestamp after and storing date as a string would give me additional problems
So is there any way to trick ballerina in order to achive this json containing a date value ?
-----here is snapshot of the code giving me the error-----
It says:
incompatible types: expected 'json', found 'ballerina/time:Time'
JSON is a text format that is completely language independent (see e.g. json.org).
time:Time is a Ballerina language specific type JSON knows nothing about. Because there is no implicit conversion (for a good reason) one have to provide the conversion.
In this case you most likely want to convert time:Time to a ISO 8601 string presentation with time:toString.
The following code (Ballerina 1.2):
import ballerina/io;
import ballerina/time;
public function main() {
var btime = time:currentTime();
var j = <json> {
time: time:toString(btime)
};
io:println(j.toJsonString());
}
Correctly prints:
{"time":"2020-06-03T08:39:07.897+03:00"}
Maryam Ziyad has written a good introduction to Ballerina's JSON support.
The following code is updated for Ballerina Swan Lake Update 1 (2201.1.0) to show how to convert a Ballerina UTC time (time:Utc) to JSON representation. Note that it's also possible to use localized time (time:Civil) but that is no different from time to JSON conversion point of view.
One can read more about Ballerina time handling from the documentation of time module.
import ballerina/io;
import ballerina/time;
public function main() {
time:Utc now = time:utcNow(3);
json j = {
time: time:utcToString(now)
};
io:println(j.toJsonString());
}
That correctly prints:
{"time":"2022-07-20T06:03:46.078Z"}

Selecting random greeting from reading a JSON file using python

I have a JSON file looking like this which i have to randomise so that every time any input comes it shows any random output from the 3 in the json file.
{
"1":"Welcome",
"2":"Hello",
"3":"Hi"
}
I read the JSON file
greeting_template1=readjson(input_file_path+'greeting_template1.json')
and to randomise
greeting_template1 = random.choice(greeting_template1)
But I am getting the error:
greeting_template1 = random.choice(greeting_template1)
File "C:\Users\\AppData\Local\Continuum\anaconda3\envs\lib\random.py", line 262, in choice
return seq[i]
KeyError: 2
Please highlight where I am going wrong
As others have pointed out your JSON is not valid.
Valid json file would be:
{
"1":"Welcome",
"2":"Hello",
"3":"Hi"
}
And the code to get a random would look something like:
import json
import random
with open('greeting_template1.json') as json_file:
data = json.load(json_file)
random_greeting = data[random.choice(list(data))]
The reason you are getting error is because random.choice() needs a sequence as an argument. Parsing a json gives you a python dictionary which is not a sequence.
Your document has 3 JSONs in it, not one. Once you close the initial {, that is your JSON. You need to rewrite to:
{
"1":"Welcome",
"2":"Hello",
"3":"Hi"
}

extract a concrete part of a value from a Response to a new string Groovy script

I'm kinda new in groovy and I need help
I need to write a groovy script to transform or else extract a concrete value from a Json Response to a new string Groovy script.
and the groovy script I used is this one :
responseJson = testRunner.testCase.getTestStepByName("Test Scenario").getPropertyValue("response")
parsedResponse = slurper.parseText(responseJson)
log.info(parsedResponse["items"]["/ticket_id"])
My generated string response from the groovy script I use looks like this:
/ticket_id":"{\"isTodo\":false,\"items\":[[\"WhatIwantToExtract\",\"\",\"url.com:blablabla_qc_vpc-11:Machine:data-da-data\",timestamp]]}
The response is correct in fact but I just want to extract a piece of this
The data I wanted to extract is labeled above as " WhatIwantToExtract " without the commas.
I solved it
def regexResult = (parsedResponse["items"][0][0])

Parse a JSON file with ISODate in Python

I have a JSON file with some lines like:
"updatedAt" : ISODate("2018-11-20T09:32:16.732+0000"),
I tried json.loads but it has an error json.decoder.JSONDecodeError: Expecting value: line 2 column 13 (char 15).
I believe that the problem is at ISODate () but how could I handle that with Python?
Many thanks
This is not valid JSON, to begin with. I guess the ISODATE("...") is generated from MongoDB, maybe dumping the ISODate() helper directly instead of its string representation into the JSON?
In any case, you could use a regex on the whole JSON-string to get rid of the ISODate("..."), retrieve the date as a string and then use python-dateutil to parse the value to a datetime.datetime.
Something to the tune of
import json
import dateutil.parse
import re
json_str = ....
clean_json = re.compile('ISODate\(("[^"]+")\)').sub('\\1', json_str)
json_obj = json.loads(clean_json)
# use dateutil.parser.parse(s) to parse each date into a datetime.datetime

Ambiguous format output in nodejs

I am having output in following format as
"[{"a":"a1"},{"a":"a2"}]"
I want to actually extract it in array of json:
[
{
"a":"a1"
},
{
"a":"a2"
}
]
How to convert it?
You have tagged this with Node-RED - so my answer assumes that is the environment you are working in.
If you are passing a message to the Debug node and that is what you see in the Debug sidebar, that indicates your msg.payload is a String with the contents of [{"a":"a1"},{"a":"a2"}] - the Debug sidebar doesn't escape quotes when displaying strings like that.
So you likely already have exactly what you want - it just depends what you want to do with it next.
If you want to access the contents you need to parse it to a JavaScript Object. You can do this by passing your message through a JSON node.
Assuming your input contains the double quotes in the beginning and end, it is not possible to directly JSON.parse() the string.
In your case, you need to remove the first and last character (the double quotes) from your string before parsing it.
const unformattedString = '"[{"a":"a1"},{"a":"a2"}]"'
const formattedString = unformattedString.substr(1, unformattedString.length - 2)
const json = JSON.parse(formattedString)
The variable json now contains your JSON object.
I would suggest a different method which will get your work done without using any third party library.
var a = '[{"a":"a1"},{"a":"a2"}]';
var b = JSON.parse(a);
console.log(b); // b will return [{"a":"a1"},{"a":"a2"}]
Another way which is eval function which is generally not recommended
var d = eval(a);
If you want to use JQuery instead use :
var c = $.parseJSON(a);