Adding a attribute to json file - json

I have a json file of the format
{"latitude":28.488069,"longitude":-81.407208,"data":[{"time":1462680000,"summary":"Clear"},{"time":1462683600,"summary":"Clear",},{"time":1462694400,"summary":"Clear"}]}}
I want to add id attribute inside data
val result = jsonfile
val Jsonobject = Json.parse(result).as[JsObject]
val res = Jsonobject ++ Json.obj("id" -> 1234)
println(Json.prettyPrint(res))
the output should be
{"latitude":28.488069,"longitude":-81.407208,"data":[{"time":1462680000,"summary":"Clear","id":"1234"},{"time":1462683600,"summary":"Clear","id":"1235"},{"time":1462694400,"summary":"Clear","id":"1236"}]}
but my output is
{"latitude":28.488069,"longitude":-81.407208,"data":[{"time":1462680000,"summary":"Clear"},{"time":1462683600,"summary":"Clear",},{"time":1462694400,"summary":"Clear"}]},"id":"1234"}

There are a couple of things missing in your code. In your expected output, the ID is incremented, how do you expect to just add "id" -> 1234 and have it automatically incremented ?
Anyway, you have to loop through the elements in data and set it for each one of them. Something like this works:
val j = Json.parse(result).as[JsObject]
val res = j ++ Json.obj("data" ->
// get the 'data' array and loop inside
(j \ "data").as[JsArray].value.zipWithIndex.map {
// zipWithIndex lets us use the index to increment the ID
case (x,i) => x.as[JsObject] + ("id" , JsString((1234 + i).toString)) })
println(Json.prettyPrint(res))
{
"latitude" : 28.488069,
"longitude" : -81.407208,
"data" : [ {
"time" : 1462680000,
"summary" : "Clear",
"id" : "1234"
}, {
"time" : 1462683600,
"summary" : "Clear",
"id" : "1235"
}, {
"time" : 1462694400,
"summary" : "Clear",
"id" : "1236"
} ]
}

Related

Python JSON Parsing example

{
"fruits" : {
"fruit" : [
{
"name" : "apple",
"size" : 1,
"price" : 1
},
{
"name" : "banana",
"size" : 1,
"price" : 2
}
]
},
"sports" : {
"sport" : [
{
"name" : "baseball",
"population" : 9
},
{
"name" : "soccer",
"population" : 11
}
]
}
}
This is my example json file.
I made this file.
If this format is not JSON, please tell me.
I want to get name's value. Using Python.
I can read JSON file and be converting dictionary.
But can't read Specific (tag's maybe) value
import json
#json file reading
with open('C:\Users\sub2\Desktop\example.json') as data_file:
data = json.load(data_file)
#dictionary key
dic_key = []
for i in data:
dic_key.append(i)
#dictionary value
for i in dic_key:
print data[i]
#name tag
for i in dic_key:
for j in data[i]:
print j.get('name')
How do get the name's value.
This should give you all names
import json
#json file reading
with open('out.json') as data_file:
data = json.load(data_file)
#dictionary key
dic_key = []
for i in data:
dic_key.append(i)
#dictionary value
for i in dic_key:
print data[i]
#name tag
for i in dic_key:
for j in data[i]:
for k in data[i][j]:
print k.get('name')

Qt: Multi Array (from JSON); get to specific child

I have the following json
(from Google Distance API)
{
"destination_addresses" : [ "Hannover, Deutschland" ],
"origin_addresses" : [ "Wolfsburg, Deutschland" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "88,8 km",
"value" : 88790
},
"duration" : {
"text" : "58 Minuten",
"value" : 3473
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
And like to get the distance values ('text' and 'value')
When I iterate that QJsonArray like that:
QJsonDocument document = QJsonDocument::fromJson(bts);
QJsonObject jsonObject = document.object();
QJsonArray jsonArray = jsonObject["rows"].toArray();
foreach (const QJsonValue & value, jsonArray) {
QJsonObject obj = value.toObject();
foreach (const QJsonValue & v, obj["elements"].toArray()) {
QJsonObject obj2 = v.toObject();
qDebug() << obj2["distance"];
//returns [1]
qDebug() << obj2["distance"].toArray();
//returns [2]
}
}
I should be able to get the values.
However, instead I get this:
[1] =
QJsonValue(object, QJsonObject({"text":"88,8 km","value":88790}) )
[2] =
QJsonArray()
which seems to be empty.
I dont know why that is. Because I do it just like that when getting to the "elements" array from that Json.
About [1]:
obj2["distance"] is an object, not array, with fields "text" and "value", and you should do one more job:
QJsonObject obj2 = v.toObject();
QJsonObject finalObject = obj2["distance"].toObject();
QString text = finalObject["text"].toString();
int value = finalObject["value"].toInt();
or something like this.
[{}, {}, {}] - an array of objects
{"a":{}, "b":{},"c":{}} - object which contains 3 objects.

Convert List to a specific JSON format in Play framework using Scala

I've a List of a type which contains three fields (services, total, improved). When I convert it to JSON using Json.toJson(myList), I get the JSON in the following format:
[
{
"services":"S4",
"total":1,
"improved":1
},
{
"services":"S1",
"total":2,
"improved":1
},
{
"services":"S2",
"total":3,
"improved":2
}
]
Using JSON library in Play 2.x in Scala, how can I convert myList in the following JSON format?
[
{
"key" : "total",
"values" :[
{
"services" : "s1",
"value" : 2
},
"services" : "s2",
"value" : 3
{
"services" : "s4",
"value" : 1
}
]
},
{
"key" : "improved",
"values" :[
{
"services" : "s1",
"value" : 1
},
"services" : "s2",
"value" : 2
{
"services" : "s4",
"value" : 1
}
]
}
]
Thanks in advance.
Since you are already dealing with OO, I think you could wrap your List into a more specific object and convert it to JSON :
case class Foo(services: String, total: Int, improved: Int)
case class B(key: String, value: Int)
case class A(key: String, values: Seq[B] = Seq())
val myOriginalList = Seq(Foo("S4", 1, 1), Foo("S1", 2, 1), Foo("S2", 3, 2))
val transformedList = myOriginalList.foldLeft((A("total"), A("improved")))({ (res, x) =>
(res._1.copy(values = B(x.services, x.total) +: res._1.values),
res._2.copy(values = B(x.services, x.improved) +: res._2.values))
}).map({x => List(x._1, x._2)})
Json.toJson(transformedList)
One of the problem (or maybe not) using this solution, is that you don't resolve the Foo attributes dynamically.
You could also try yourself around Json Transformers : http://www.playframework.com/documentation/2.2.x/ScalaJsonTransformers
Here's a Scala newbie's solution (I'm sure it's not elegant):
I'm using a solution provided here: http://www.playframework.com/documentation/2.1.1/ScalaJson
//some data
case class PatientAggregateValues(total: Int, improved: Int)
val scoreMap = Map.empty[String, PatientAggregateValues]
scoreMap += ("S1" -> PatientAggregateValues(2, 1))
scoreMap += ("S2" -> PatientAggregateValues(3, 2))
scoreMap += ("S4" -> PatientAggregateValues(1, 1))
//main logic
val totalMap = scoreMap map { case (k,v) => Json.toJson(scala.collection.immutable.Map("service" -> Json.toJson(k), "value" -> Json.toJson(v.total))) } toSeq
val improvedMap = scoreMap map { case (k,v) => Json.toJson(scala.collection.immutable.Map("service" -> Json.toJson(k), "value" -> Json.toJson(v.improved))) } toSeq
Json.toJson(scala.collection.immutable.Map("total" -> totalMap, "improved" -> improvedMap))
Thanks.

How do I transform json using scala lift?

How do I transform the json below using scala lift based on a sibling attribute?
In the json below, I want to encode the value in "value" attribute if sibling attribute "type" is "html"
val json = """
{
"id" : "1B23423B",
"payload" : {
"list" : [ {
"name" : "test",
"data" : [ {
"value" : "Some html",
"type" : "html",
}, {
"value" : "some text",
"type" : "text"
}]
}]
}
}
"""
def encode(s:String):String = s + "encoded"
val newjson = js.transform {
case x if x == JField("type",JString("html")) => // somehow encode value??
}
println(newjson)
Here is on of the possible solutions:
1) first find data json with type html
2) transform json value child
val parsed = JsonParser.parse(jsonString)
def encode(s:String):String = s + "encoded"
private def encodeValue(dataObject: JValue) = dataObject.transform{
case JField("value", JString(value)) => JField("value", JString(encode(value)))
}
val newJson = parsed.transform({
case dataObject # JObject(fields) if fields.contains(JField("type", JString("html"))) => encodeValue(dataObject)
})

Playframework play.api.libs.json.Json.format real use case

I want to convert my stuff:
case class Message (
var text: String = "",
var `type`: String = "error"
)
case class ValidationFieldError(
var fieldName:String, message:Message,
var value:String = "",
var suggestions:List[String] = List[String]()
)
to json object ...
import play.api.libs.json.{Json, JsValue}
.. Here I try to use Json.format
implicit val validationFieldErrorFormat = Json.format[Message]
implicit val validationFieldErrorFormat = Json.format[ValidationFieldError]
..
when I do Json.toJson(errors) I get json array back. That's good. By I want to get json object back. To get back json structure like this:
{
"email": {
"message": {"type": "error", "text": "email duplication"},
"value": "",
"suggestions": [ ]
},
"username" : {... etc. }
}
I've been trying experimenting with it but gave up for now. Using StringBuilder to get desired json.
Q: what would be the way to make such a structure / transformation.
You can do something like that:
Json.obj(
"email" -> Json.obj(
"message" -> Json.obj("type" -> "error", "text" -> "email duplication"), // or use Json.toJson(your object)(implicit format) with desired Format
"value" -> "",
"suggestions" -> Seq()
),
"username" -> Json.obj(...)
)