Parse json in node js - json

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

Related

Assign array to JSON object as a new object

I have an array which includes some values, ex.
let array = [value1, value2];
How can I create a JSON object like the following?
{
"field": "[value1, value2]"
}
Use JSON.stringify() method:
let array = [value1, value2];
let yourJObject={"field":JSON.stringify(array)}
JSON.stringify for output a json, ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
I think you could find it pretty easily with a Google search :)
const result = JSON.stringify({ field: ["toto", "tutu"]})
console.log(result)

how to stringify json in flutter

In flutter(dart), it is easy to deserialize Json and get a token from it, but when I try to serialize it again, the quotation marks around the keys and values with disappear.
String myJSON = '{"name":{"first":"foo","last":"bar"}, "age":31, "city":"New York"}';
var json = JSON.jsonDecode(myJSON); //_InternalLinkedHashMap
var nameJson = json['name']; //_InternalLinkedHashMap
String nameString = nameJson.toString();
Although the nameJson have all the double quotations, the nameString is
{first: foo, last: bar}
(true answer is {"first": "foo", "last": "bar"})
how to preserve Dart to remove the "s?
When encoding the object back into JSON, you're using .toString(), which does not convert an object to valid JSON. Using jsonEncode fixes the issue.
import 'dart:convert';
void main() {
String myJSON = '{"name":{"first":"foo","last":"bar"}, "age":31, "city":"New York"}';
var json = jsonDecode(myJSON);
var nameJson = json['name'];
String nameString = jsonEncode(nameJson); // jsonEncode != .toString()
print(nameString); // outputs {"first":"foo","last":"bar"}
}

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

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

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