I am trying to define an initial JSON structure with a list and dictionaries. My code is as below:
import json
transactionSubmission = {}
documentDetails = []
documentDetails_dict = {}
generalDetails = {}
documentDetails_dict.update(generalDetails)
documentDetails.append(documentDetails_dict)
transactionSubmission.update({'documentDetails': [documentDetails]})
transactionSubmission_json = json.dumps(transactionSubmission)
print(transactionSubmission_json)
I am getting output as below:
{
"documentDetails": [
[
{
}
]
]
}
But i am expecting an output as below:
{
"documentDetails": [
{
"generalDetails": {}
}
]
}
Appreciate any help on this please..
This fixes what you are trying to do:
import json
transactionSubmission = {}
documentDetails = []
documentDetails_dict = {}
generalDetails = {}
documentDetails_dict['generalDetails'] = generalDetails
documentDetails.append(documentDetails_dict)
transactionSubmission['documentDetails'] = documentDetails
transactionSubmission_json = json.dumps(transactionSubmission)
print(transactionSubmission_json)
Output:
{"documentDetails": [{"generalDetails": {}}]}
But you can simplify things:
import json
transaction = {'documentDetails':[{'generalDetails':{}}]}
print(json.dumps(transaction))
print(json.dumps(transaction,indent=2)) # for readability
Output:
{"documentDetails": [{"generalDetails": {}}]}
{
"documentDetails": [
{
"generalDetails": {}
}
]
}
Related
Want to validate in Karate framework
For the below Json What I want to validate is,
if "isfilter_regex":0 then "msgtype": "##regex ^[A-Za-z0-9_.]-/*"
or if "isfilter_regex":1 then "msgtype": "#string"
(when isfilter_regex = 1 then msgtype must be a regular expression)
In my case number of candidate s in candidates array is 180+
I tried lot of things I ended up failing can anybody help me here?
{
"candidates":[
{
"candidate":{
"name":"Alex",
"category":[
{
"category_name":"APCMRQ",
"filters":[
{
"isfilter_regex":0,
"msgtype":"APCMRQ"
}
]
},
{
"category_name":"BIDBRQ",
"filters":[
{
"isfilter_regex":1,
"msgtype":"'(AMSCNQ(_[A-Za-z0-9]{1,3}){0,3})'"
}
]
}
]
}
}
]
}
I tried below way which works only when idex specified, but what to do if I want to do this check for entire array?,
* def msgRegexValue = response.candidates[150].candidate.category[0].filters[0].isfilter_regex
* def actualFilter = response.candidates[150].candidate.category[0].filters[0]
* def expectedFilter = actualFilter
* def withRegex =
"""
{
"isfilter_regex": 0,
"msgtype": '##regex ^[A-Za-z0-9_.]*-*/*'
}
"""
* def withoutRegex =
"""
{
"isfilter_regex": 1,
"msgtype": '##string'
}
"""
* def expected = msgRegexValue == 0 ? withRegex: withoutRegex
* match actualFilter == expected
In terraform I have an external data source
data "external" "example" {
program = [
"some_program_generating_json"
]
}
some_program_generating_json produces the following output:
{
"dict1": {
"key1": "value1"
},
"dict2": {
"key1": "value2"
}
}
How can I extract the value of [dict1][key1] from that data source and assign it to some local?
lets say:
locals {
extracted_value = ???
}
Thanks.
I tested it, and had no problems using [dict1][key1] notation. This is the example I used.
script file (test.sh)
#!/usr/bin/bash
# from https://github.com/hashicorp/terraform/issues/13991#issuecomment-526869879
printf '{"base64_encoded":"%s"}\n' $(echo '{"dict1": {"key1": "value1"}, "dict2": {"key1": "value2"}}' | base64 -w 0)
main.tf
data "external" "example" {
program = [
"${path.module}/scripts/test.sh"
]
}
locals {
json_value = jsondecode(base64decode(data.external.example.result["base64_encoded"]))
dict1_key1 = local.json_value["dict1"]["key1"]
}
output "result" {
value = local.dict1_key1
}
The output was:
result = value1
Seems like I figured it out. I had to convert values of dict1 and dict2 to strings:
{
"dict1": "{\"key1\": \"value1\"}",
"dict2": "{\"key1\": \"value2\"}"
}
and then use jsondecode on them. I.e.
locals {
key = "dict1"
extracted_dict = jsondecode("${data.external.example.result[local.key]}")
extracted_value = local.extracted_dict["key1"]
}
I have a json file containing contact info grouped by city. I want to parse the json and create a list of names and numbers but after fiddling for an hour or so, I can't get this to work in groovy.
def json = '''{
"date":"2018-01-04T22:01:02.2125",
"boston": [
{
"name":"bob",
"phone":"242 123123",
"ext":"12",
"email":"bob#boston.com"
},
{
"name":"alice",
"phone":"212-123-345",
"ext":"1",
"email":"alice#boston.com"
}
],
"chicago": [
{
"name":"charlie",
"phone":"313-232-545",
"ext":"14",
"email":"charlie#chicago.com"
},
{
"name":"denise",
"phone":"414-123-546",
"ext":"9",
"email":"denise#chicago.com"
}
]
}'''
I have tried a few variations on the following theme but they all failed so far.
parsedjson = slurper.parseText(json)
phonelist = []
parsedjson.each{phonelist.add([it['name'],it['phone']])}
It's tricky with the json you have, as you need to look for the values which are lists... You can do this with a findAll, so given the json:
def json = '''{
"date":"2018-01-04T22:01:02.2125",
"boston": [
{
"name":"bob",
"phone":"242 123123",
"ext":"12",
"email":"bob#boston.com"
},
{
"name":"alice",
"phone":"212-123-345",
"ext":"1",
"email":"alice#boston.com"
}
],
"chicago": [
{
"name":"charlie",
"phone":"313-232-545",
"ext":"14",
"email":"charlie#chicago.com"
},
{
"name":"denise",
"phone":"414-123-546",
"ext":"9",
"email":"denise#chicago.com"
}
]
}'''
You can import the JsonSlurper and parse the json as you currently do:
import groovy.json.JsonSlurper
def parsedjson = new JsonSlurper().parseText(json)
Then;
def result = parsedjson.findAll { it.value instanceof List } // Find all entries with a list value
.values() // Get all the lists
.flatten() // Merge them into a single list
.collect { [it.name, it.phone] } // grab the name and phone for each
I'm new to groovy. I'm trying to split the values in json object in groovy but i cant seem to find a solution. Please find the sample code below
def inputFile = new File("C:\\graph.json")
def InputJSON = new JsonSlurper().parseFile(inputFile,'UTF-8')
InputJSON.each{println it}
def names = InputJSON.graph;
def name
for (int kk=0;kk<4;kk++)
{
name=names.JArray1[kk]
run.put(name.runid, name.rundetails);
println "test::"+name.runid+"--------------"+name.rundetails
}
graph.json
{
"graph": {
"JArray1": [
{
"runid": 1,
"rundetails":{
"01_Home":0.231,
"02_Login":0.561}
}
]
}
}
name.rundetails contains the below values
[01_Home:0.231, 02_Login:0.561]
I would like to split and add it as key and value in Hashmap like below format
Key:01_Home Value:0.231
Key:02_Login Value:0.561
How would i do that any advise on this would be helpful. Thanks in advance.
import groovy.json.*
def inputFile = new StringReader('''
{
"graph": {
"JArray1": [{
"runid": 1,
"rundetails": {
"01_Home": 0.231,
"02_Login": 0.561
}
}
]
}
}
''')
def json = new JsonSlurper().parse(inputFile)
json.graph.JArray1.each{run->
println "runid = ${run.runid}"
// at this point `run.rundetails` is a map like you want
println "details = ${run.rundetails}"
}
As I understand you need collection like:
[[Key:01_Home, Value:0.231], [Key:02_Login, Value:0.561]]
Then you may do:
println InputJSON.graph
.JArray1
.rundetails
.collectEntries{it}
.collect{[Key: it.key, Value: it.value]}
I'm working on a Scala program that uses the Scala Pickling library to serialize and deserialize a Map object that contains a String and a Point2D.Double object from the java.awt.geom package.
Here's the relevant logic:
contents +=
new Button("Save Config") {
reactions += {
case ButtonClicked(_) => {
var m: Map[String, Point2D.Double] = Map()
nodeFields.foreach(x => {
m += (x._1 -> new Point2D.Double(x._2._1.text.toDouble, x._2._2.text.toDouble))
})
val pkl = m.pickle
fc.showSaveDialog(null)
val outputFile = fc.selectedFile
val writer = new PrintWriter(outputFile)
writer.write(pkl.value)
writer.close()
Dialog.showMessage(null, "Success!")
}
}
}
If you need to see more, here's the commit with the offending logic
As it stands, the JSON formatted string output from pkl.value is a working serialized Map[String, Point2D.Double], except that the values of Point2D.Double are dropped!
Here's a snippet of the output:
{
"$type": "scala.collection.mutable.Map[java.lang.String,java.awt.geom.Point2D.Double]",
"elems": [
{
"$type": "scala.Tuple2[java.lang.String,java.awt.geom.Point2D.Double]",
"_1": "BOTTOMLANE\r",
"_2": {
}
},
{
"$type": "scala.Tuple2[java.lang.String,java.awt.geom.Point2D.Double]",
"_1": "UPPERLANESECOND_0\r",
"_2": {
}
},
{
"$type": "scala.Tuple2[java.lang.String,java.awt.geom.Point2D.Double]",
"_1": "upperSecondTower_1",
"_2": {
}
},
...
]
}
What can I do to fix this?
scala-pickling can not directly pickle/unpickle Point2D.Double because it has no public fields (the x and y values are accessible through the getX and getY getters).
A possible Pickler / Unpickler for Point2D.Double would be :
object Point2DPickler {
import scala.pickling._
import scala.pickling.Defaults._
import java.awt.geom.Point2D
type DoublePoint = java.awt.geom.Point2D.Double
implicit object Point2DDoublePickle extends Pickler[DoublePoint] with Unpickler[DoublePoint] {
private val doubleUnpickler = implicitly[Unpickler[Double]]
override def tag = FastTypeTag[java.awt.geom.Point2D.Double]
override def pickle(point: DoublePoint, builder: PBuilder) = {
builder.beginEntry(point)
builder.putField("x",
b => b.hintTag(FastTypeTag.Double).beginEntry(point.getX).endEntry()
)
builder.putField("y",
b => b.hintTag(FastTypeTag.Double).beginEntry(point.getY).endEntry()
)
builder.endEntry()
}
override def unpickle(tag: String, reader: PReader): DoublePoint = {
val x = doubleUnpickler.unpickleEntry(reader.readField("x")).asInstanceOf[Double]
val y = doubleUnpickler.unpickleEntry(reader.readField("y")).asInstanceOf[Double]
new Point2D.Double(x, y)
}
}
}
Which could be used as :
import scala.pickling.Defaults._
import scala.pickling.json._
import java.awt.geom.Point2D
import Point2DPickler._
val dpoint = new Point2D.Double(1d, 2d)
scala> val json = dpoint.pickle
json: pickling.json.pickleFormat.PickleType =
JSONPickle({
"$type": "java.awt.geom.Point2D.Double",
"x": {
"$type": "scala.Double",
"value": 1.0
},
"y": {
"$type": "scala.Double",
"value": 2.0
}
})
scala> val dpoint2 = json.value.unpickle[java.awt.geom.Point2D.Double]
dpoint2: java.awt.geom.Point2D.Double = Point2D.Double[1.0, 2.0]