Firebase - JSON sent object results escaped - json

When I .set(jsonObject) into Firebase DB, using angularfire2, the object is escaped(backslashes are added before each double quote).
When I manually add the jsonObject into DB(console.firebase.google.com) everything works fine.
let obj = {
key0 : 0,
key1 : 1
};
console.log(obj);
let jsonObject = JSON.stringify(obj);
console.log(jsonObject);
// af is AngularFire instance
af.database.object("/myList/0").set(jsonObject)
The result in Firebase DB Console is: "{\"key0\":0,\"key1\":1}"
But I get the expected result when I go to Firebase DB Console and replace the escaped object with the values from console.log(jsonObject).
What is the problem?
Thank you

If you are setting the value this way:
let obj = {
key0 : 0,
key1 : 1
};
let jsonObject = JSON.stringify(obj);
af.database.object("/myList/0").set(jsonObject);
The value at /myList/0 will be a string:
{"key0":0,"key1":1}
The values shown in the console will be shown as JSON. When formatted as JSON, the above string value will be:
"{\"key0\":0,\"key1\":1}"
If you set the value using the object and not the JSON string, you should see the behaviour you are expecting:
let obj = {
key0 : 0,
key1 : 1
};
af.database.object("/myList/0").set(obj);

Related

extracting data from Json file

I am using a child process to execute a script and I have this result in stdout. Using res.json(stdout) to send this output to the variable data in app.component. How can I extract data from this output using data.TradeId for example knowing that the variable data is an object.
Console.log(data)
Query Result: {"TradeId":"FTE_2","BuyerTaxId":"ABC
Firm","Skuid":"SKU001","SellerTaxId":"CDE
Firm","ExportBankId":"","ImportBankId":"","DeliveryDate":"","ShipperId":"","Status":"Trade
initiated","TradePrice":10000,"ShippingPrice":1000}
So assuming "data" is a string (because you say console.log(data) equals the given output), you could do something like:
// This will be the data variable you already have
const data = `Query Result: {"TradeId":"FTE_2","BuyerTaxId":"ABC Firm","Skuid":"SKU001","SellerTaxId":"CDE Firm","ExportBankId":"","ImportBankId":"","DeliveryDate":"","ShipperId":"","Status":"Trade initiated","TradePrice":10000,"ShippingPrice":1000}`;
// Replace the prefixed string from the JSON string
const jsonString = data.replace("Query Result: ", "");
// Parse the json string into a json object
const jsonObject = JSON.parse(jsonString);
// At last, you can simply get the TradeId from your JSON object
const tradeId = jsonObject.TradeId;
console.log(tradeId); //results in: FTE_2

JSON parsing collection of records

I've been struggling with this for long, I believe there's something wrong with my record design.
MY json looks like below. I posted this earlier as a part of another question but didn't get full answer especially for this part. Each record within the array is an object with a field name with data of type string.
JSON
[
{
"data": "/publication/a40a5e5c-98b3-45ae-d6a3-924b31d8712a/article/test;version=1521246543034"
},
{
"data": "/publication/a40a5e5c-98b3-45ae-d6a3-924b31d8712a/book/test2;version=1520623346891"
},
{
"data": "/publication/a40a5e5c-98b3-45ae-d6a3-924b31d8712a/catalog/test3;version=1520623346833"
}
]
List.fs
open System.Runtime.Serialization
[<DataContract>]
type List= {
[<field: DataMemberAttribute(Name="data") >]
Data: string
}
Parsing JSON
let response = request.GetResponse() :?> HttpWebResponse
use reader = new StreamReader(response.GetResponseStream())
use memoryStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(reader.ReadToEnd()))
let jsonSerializer = DataContractJsonSerializer(typeof<List[]>)
let result = jsonSerializer.ReadObject(memoryStream) :?> List[]
Debug.WriteLine(sprintf "%A" result)
Actual Output - having nulls
[|
{Data = null;};
{Data = null;};
{Data = null;}
|]
Expected Output
[|
{Data = "/publication/a40a5e5c-98b3-45ae-d6a3-924b31d8712a/article/test;version=1521246543034";};
{Data = "/publication/a40a5e5c-98b3-45ae-d6a3-924b31d8712a/book/test2;version=1520623346891";}
{Data = "/publication/a40a5e5c-98b3-45ae-d6a3-924b31d8712a/catalog/test3;version=1520623346833";}
|]
Iteration
result
> Array.iter (fun x -> Console.WriteLine(x.Href))
I suspect there must be something wrong with how you're reading the data. I tried to reproduce this and replaced the reading from a stream with reading from a string - so that I can test this - and the following works fine (in F# interactive version 14.0.23413.0):
#r "System.Runtime.Serialization"
open System.IO
open System.Text
open System.Runtime.Serialization
open System.Runtime.Serialization.Json
[<DataContract>]
type List= {
[<field: DataMemberAttribute(Name="data") >]
Data: string
}
let reader = new StringReader("""[
{ "data": "/publication/a40a5e5c/article/test;version=1521246543034" },
{ "data": "/publication/a40a5e5c/book/test2;version=1520623346891" },
{ "data": "/publication/a40a5e5c/catalog/test3;version=1520623346833" } ]""")
let memoryStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(reader.ReadToEnd()))
let jsonSerializer = DataContractJsonSerializer(typeof<List[]>)
let result = jsonSerializer.ReadObject(memoryStream) :?> List[]
result
Can you check that your input JSON is actually the one you shared here? To do that, see what reader.ReadToEnd() returns before calling GetBytes - I suspect there must be something wrong there, because the rest of the code works fine for me.

how to use SwiftyJSON framework to read a locally declared JSON

I am trying to read a locally declared JSON, since I still do not have the network ready to send me JSON examples for the app we are developing.
For some reason I get a null when trying to print the json created by SwiftyJSON framework.
This is my class:
import Foundation
import SwiftyJSON
let mockShifts = "{\"numOfShiftsInDay\": 3,\"shifts\": [{\"StartTime\": \"06:30\",\"EndTime\": \"14:00\"},{\"StartTime\": \"14:00\",\"EndTime\": \"19:00},{\"StartTime\": \"19:00\",\"EndTime\":\"01:00\"}]}"
class WeeklySchedule {
var shifts: [Shift] = []
var shiftsAmount: Int = 3
var relative: Int = 0
func setShiftsAmount(amount: Int){
self.shiftsAmount = amount
for _ in 1...amount{
self.shifts.append(Shift())
}
getShifts()
}
func getRelative() -> Int{
return relative
}
func getShifts(){
let data = mockShifts.data(using: .utf8)!
let json = JSON(data: data)
print(mockShifts) //This prints out a JSON that looks OK to me
print(json) //This prints NULL
if let numOfShifts = json["numOfShiftsInDay"].string {
print(numOfShifts) //This code is unreachable
}
}
}
And this is my console output, when calling setShiftsAmount() which calls getShifts():
{"numOfShiftsInDay": 3,"shifts": [{"StartTime": "06:30","EndTime": "14:00"},{"StartTime": "14:00","EndTime": "19:00},{"StartTime": "19:00","EndTime":"01:00"}]}
null
Why is my JSON null?
The reason you are getting null for your JSON because your JSON string mockShifts is not contain's valid JSON, there is missing double quote(\") for the EndTime key after 19:00 in the second object of array shifts. Add that double quote and you all set to go.
let mockShifts = "{\"numOfShiftsInDay\": 3,\"shifts\": [{\"StartTime\": \"06:30\",\"EndTime\": \"14:00\"},{\"StartTime\": \"14:00\",\"EndTime\": \"19:00\"},{\"StartTime\": \"19:00\",\"EndTime\":\"01:00\"}]}"

import JSON in Realm

I have a SQL Database on Azure and I would like to synchronize it with Realm, for my iOS App (in Swift)
For that, I have created a REST API which generates a JSON and now I would like to integrate this JSON in Realm.
To do that, I have tried to follow the explanation on Realm Documentation, so now I have :
Realm Table :
class tbl_test: Object {
dynamic var id:Int = 0
dynamic var name:String = ""
override class func primaryKey() -> String? {
return "id"
}
}
Swift Code :
let realm = try! Realm()
let stringTxt:String = "[{\"id\": 1, \"name\": \"My Name\"}]"
var myData = NSData()
if let dataFromString = stringTxt.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let jsonData = JSON(data: dataFromString)
if let encryptedData:NSData = try! jsonData.rawData() {
myData = encryptedData
}
}
try! realm.write {
let json = try! NSJSONSerialization.JSONObjectWithData(myData, options: NSJSONReadingOptions())
realm.create(tbl_test.self, value: json, update: true)
}
I use SwiftyJSON to convert my string to JSON.
When I run the program, I have this error message :
[__NSCFDictionary longLongValue]: unrecognized selector sent to
instance 0x7fdcc8785820 2016-07-06 10:25:30.090
mydrawing[9436:2732447] *** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFDictionary
longLongValue]: unrecognized selector sent to instance 0x7fdcc8785820'
Is it a good way to import JSON in Realm ? There is no official way according to what I have found, but this method should work...
The problem you're facing is that the structure of the data you're passing to Realm.create(_:value:update:) doesn't match what the method expects. It expects either a dictionary with keys corresponding to the managed properties on your model type, or an array with one element for each managed property.
After deserializing the JSON data, json looks like so:
(
{
id = 1;
name = "My Name";
}
)
That is an array containing a single element that is an dictionary. When you pass this array to Realm.create(_:value:update:), Realm expects the first element of the array to be the value to use as the id property on your tbl_test type.
I suspect that what you mean to do is to call Realm.create on each of the elements of the array in turn, instead of calling it on the array itself.

Appending values in a list and then sending as a JSON object

var jsonElements = List[String]()
val params = Map("host"->host)
for((key,value)<-mapSql){
val map = Map("metric"->key,"timestamp"->new Date().getTime,"value"->value,"tags"->params)
jsonElements=JsonUtility.toJSONString(map) :: jsonElements
}
val entity = new StringEntity(JsonUtility.toJSONString(jsonElements))
println("json elements final list is "+jsonElements)
println("json elements final JSON Obj is "+JsonUtility.toJSONString(jsonElements))
entity.setContentType(new BasicHeader("Content-Type", "application/json"))
val postRequest: HttpPost = new HttpPost(putURL)
postRequest.setEntity(entity)
val postResponse: CloseableHttpResponse = httpclient.execute(postRequest)
I basically need to add values to a list and then send them together in a JSON Array.
However this is introducing unnecessary escape characters "/" in the output which is rendering the post request useless and I am getting an error to the API hit. the following is the response :
json elements final list is List({"metric":"replicationLag","timestamp":1410179907871,"value":0.0,"tags":{"host":"tg-em-db01.nm.xxxx.com"}}, {"metric":"status","timestamp":1410179907824,"value":1,"tags":{"host":"tg-em-db01.nm.xxxxx.com"}})
json elements final JSON Obj is ["{\"metric\":\"replicationLag\",\"timestamp\":1410179907871,\"value\":0.0,\"tags\":{\"host\":\"tg-em-db01.nm.xxxx.com\"}}","{\"metric\":\"status\",\"timestamp\":1410179907824,\"value\":1,\"tags\":{\"host\":\"tg-em-db01.nm.xxxxx.com\"}}"]
I can replace and remove all the escape characters by the replaceAll function but I do not want to do that. is there a better way to append objects to an already existing JSON object and then change it to an array ( which i can easily do by new JsonArray(List(JsonObj)) ) so that i dont get any escape characters anywhere.
Something like this :
val params = Map("host"->host)
var map = Map[String,Any]()
for((key,value)<-mapSql){
map ++= Map("metric"->key,"timestamp"->new Date().getTime,"value"->value,"tags"->params)
}
val entity = new StringEntity(JsonUtility.toJSONString(List(map)))
println("json elements final list is "+map)
println("json elements final JSON Obj is "+JsonUtility.toJSONString(List(map)))
is giving me this as an ouput :
json elements final list is Map(metric -> replicationLag, timestamp -> 1410180939983, value -> 0.0, tags -> Map(host -> tg-em-db01.nm.xxxx.com))
json elements final JSON Obj is [{"metric":"replicationLag","timestamp":1410180939983,"value":0.0,"tags":{"host":"tg-em-db01.nm.xxxxx.com"}}]
But I need something like this :
[ {"metric":blah blah} , {"metric":blah blah} ]
Is there a way to append to maps such that the same key values are not clubbed ?
Thanks in advancE!
var jsonElements = List[Map[String, Any]]()
val params = Map("host" -> host)
for ((key, value) <- mapSql) {
val map = Map("metric" -> key, "timestamp" -> new Date().getTime, "value" -> value, "tags" -> params)
jsonElements = map :: jsonElements
}
val entity = new StringEntity(JsonUtility.toJSONString(jsonElements))
entity.setContentType(new BasicHeader("Content-Type", "application/json"))
val postRequest: HttpPost = new HttpPost(putURL)
postRequest.setEntity(entity)
val postResponse: CloseableHttpResponse = httpclient.execute(postRequest)
object JsonUtility {
def toJSONString(obj:Any):String = {
compact(JsonAST.render(decompose(obj)))
}
}