extracting data from Json file - json

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

Related

How to Convert JSON to record or map type in Ballerina with JSON key names with spaces

I'm getting a JSON from [1], due to the naming of the keys in the json I was unable to straightaway use either of the 2 approches in hadling JSON in ballerina:
Approach 1: Work with json values directly:
string s = check j.x.y.z;
Approach 2: Work with application-specific, user-defined subtype of anydata:
couldn't use cloneWithType or directly assign to a user defined record type
My workaround was:
type AllStockData record {
string open;
string high;
string low;
string close;
string volume;
};
AllStockData[] stockData = [];
public function main() returns #tainted error? {
http:Client httpClient = check new ("https://www.alphavantage.co");
json jsonPayload = check httpClient->get("/query?function=TIME_SERIES_INTRADAY&symbol="+searchSymbol.toUpperAscii()+"&interval=5min&apikey="+apiKey, targetType = json);
map<json> allData = <map<json>>jsonPayload;
foreach json item in <map<json>>allData["Time Series (5min)"] {
map<json> stockItem = <map<json>>item;
AllStockData stock = {
open: stockItem["1. open"].toString(),
high: stockItem["2. high"].toString(),
low: stockItem["3. low"].toString(),
close: stockItem["4. close"].toString(),
volume: stockItem["5. volume"].toString()
};
stockData.push(stock);
}
I was wondering If there is a better way to do this?
I prefer to work with application-specific types when dealing with JSON in Ballerina. You can use quoted identifiers in Ballerina to map the complete json payload into an application-specify type. I've used a query expression to filter out stack data entries into an array. There are other ways with slight variations to achieve the same thing.
Note that I've used Ballerina Swan Lake Alpha 3 to test this code.
import ballerina/io;
import ballerina/http;
type StockQuery record {|
MetaData 'Meta\ Data;
TimeSeries5min 'Time\ Series\ \(5min\);
|};
type MetaData record {|
string '1\.\ Information;
string '2\.\ Symbol;
string '3\.\ Last\ Refreshed;
string '4\.\ Interval;
string '5\.\ Output\ Size;
string '6\.\ Time\ Zone;
|};
type TimeSeries5min record {|
StockData...;
|};
type StockData record {|
string '1\.\ open;
string '2\.\ high;
string '3\.\ low;
string '4\.\ close;
string '5\.\ volume;
|};
public function main() returns error? {
http:Client httpClient = check new ("https://www.alphavantage.co");
json jsonPayload = check httpClient->get("/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=demo",
targetType = json);
StockQuery stockQuery = check jsonPayload.cloneWithType(StockQuery);
TimeSeries5min timeSeries = stockQuery.Time\ Series\ \(5min\);
StockData[] stockDataArr = from var key in timeSeries.keys()
let StockData? stockData = timeSeries[key]
where stockData is StockData
select stockData;
io:println(stockDataArr);
}

Parse json in node js

Can someone help me with this json {"event":"update","data":"{\"asks\":[[\"55.5\",\"5.3744\"],[\"55.74\",\"0.8087\"]]}}, how parse this values from json 55.5 and 5.3744. I will be grateful for help.
Your JSON is invalid and cannot be parsed.
I assume your data is a JSON string within a JSON string that should be parsed after the main JSON string has been parsed. This is not really efficient and you should consider not stringifying the data value in the first place.
Your JSON should look like this:
{"event":"update","data":{"asks":[["55.5","5.3744"],["55.74","0.8087"]]}}
Or:
{\"event\":\"update\",\"data\":{\"asks\":[[\"55.5\",\"5.3744\"],[\"55.74\",\"0.8087\"]]}}
In JavaScript:
const json = '{"event":"update","data":{"asks":[["55.5","5.3744"],["55.74","0.8087"]]}}';
const obj = JSON.parse(json);
const val1 = obj.data.asks[0][0];
const val2 = obj.data.asks[0][1];
If you must have data as a JSON encoded string, encode it correctly. If you want to know what your JSON string should look like in this case, work backwards:
const dataString = JSON.stringify({
asks: [
["55.5", "5.3744"],
["55.74","0.8087"]
]
});
const jsonString = JSON.stringify({
event: "update",
data: dataString
});
// {\"event\":\"update\",\"data\":\"{\\\"asks\\\":[[\\\"55.5\\\",\\\"5.3744\\\"],[\\\"55.74\\\",\\\"0.8087\\\"]]}\"}
// And back again...
const asks = JSON.parse(
JSON.parse(jsonString).data
).asks;
const val1 = asks[0][0];
const val2 = asks[0][1];

Firebase - JSON sent object results escaped

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);

node-xmpp-server with json body messages

is there any chance to get node-xmpp-server lib to handle messages body in json format (XEP-0295)?
You can serialize json object using stringify, send it, and then unserialize it using parse method
Lets say we have jsonObject variable:
var data = {'some': 'thing', 'bla': 'blah'};
var message = JSON.stringify(data);
and unserialize:
var data = JSON.parse("some serialized message");

how to convert an object from json format to integer format

I am passing an array from view to the controller using json.stringify() method.
That value is passed to the controller and is in
"\"[{\\\"id\\\":1 "id\\\":2}]\"" format. I think this is in json format, I want to convert this into {id:1,id:2} format.
I tried to convert this into string format using JsonConvert.SerializeObject(),
but it is displaying in "\"\\\"[{\\\\\\\"id\\\\\\\":1}]\\\"\"" format.
Can you tell me how can I convert into {id:1,id:2} format/integer format?
The JSON data represents an array containing a dictionary as far as I can tell. You could get hold of a Dictionary representation of the data like this:
var json = "[{\"id\":1, \"id\": 2}]";
Dictionary<string, int>[] obj = JsonConvert.DeserializeObject<Dictionary<string, int>[]> (json);
var dict = obj[0];
I'm not sure if this is what you're after though, since you're saying that you want to display it like {id: 2}. If you want to print it out like that, you can build a string representation of the Dictionary:
var sb = new StringBuilder();
sb.Append("{");
foreach (var item in dict)
{
sb.Append(string.Format("{0}: {1}, ", item.Key, item.Value));
}
sb.Remove(sb.Length - 2, 2);
sb.Append("}");
Console.WriteLine(sb.ToString());
This prints {id: 2}.
To retrieve the value for 'id', if this is what you mean, you can do this:
var val = dict["id"];
var serializer = new JavaScriptSerializer();
var data = serializer.Deserialize<object[]>(jsonString);