how to read 3 json responses like one - json

I have 3 functions that invoke a json response
function one gives:
{
"IT_INFO": {
"CARNET": "999250 ",
"CEDULA": "000013724224",
"NOMBRE": "pedro ",
"SEGNOMBRE": "salomon ",
"APELLIDO": "Perez ",
"SEGAPELLIDO": "Perza ",
"EMAIL": "mail#mailexample.com ",
"IAP": "0.00",
"IAA": "0.00"
}
}
second function :
{
"HISTORICOP": [
{
"MATERIA": "PROCESOS DEL LENGUAJE ",
"NOTA": "7 ",
"ANIO": "2000",
"PERIODO": "001",
"ENEMENOSUNO": "Ordinaria. Estado por defecto "
}
]
}
third function:
{
"HORARIO": [
{
"CODIGO": "BERSP01 ",
"MATERIA": " COMPUTADOR ",
"AULA": "A1-102 ",
"PROFESOR": "Quintero Moros, Nelson ",
"HORARIO": "TU WE FR 08:00-10:00 "
}
]
}
How should it come out so the function JSON.parse(str) will read it?
str = [func1,func2,func3] ??
or
str = [[func1],[func2],[func3]]?
or??? any ideas???

I assume you parse the JSON in JavaScript.
Normally you should not build JSON "manually", but in this case it does not seem to be too bad:
var objs = JSON.parse('[' + [func1(), func2(), func3()].join(',') + ']');
This creates a JSON array with the three objects returned by the functions.
Alternatively you can parse the responses individually:
var objs = [func1(), func2(), func3()];
for(var i = objs.length; i--; ) {
objs[i] = JSON.parse(objs[i]);
}
Of course you have to do things differently if the functions don't return the JSON but make some Ajax request...

Related

I want to convert csv to json with key value pair

I have a JSON file as below and want to convert to json with Name key , value pair ,
Eg : "name":"emailAddress",
"value" :"Trest22#gmail.com"
If have multiple JSON tags then it should break into separate tag as shown in image.
Please help
[
{
"emailAddress": "Trest22#gmail.com",
"loginName": "Testinguser222",
"firstName": "Test222",
"surName": "Test22",
"primaryPhone": "",
"companyId": 123445,
"extracompanies": "[12311,33333]",
"middleName": "Test",
"mobilePhone": 6666666666,
"fax": 87687687686
}
]
Want to convert as below
{
{
"name":"emailAddress",
"value" :"Trest22#gmail.com"
}
{
"name":"loginName",
"value":"Testinguser222"
}
{
"name":"firstName",
"value":"Test222"
}
{
"name":"surName",
"value":"Test22"
}
{ "name":"extracompanies",
"value": "[12311,33333]"
}
I am not sure if any library can do that, however, in Java, you can achieve it as shown below,
ObjectMapper mapper = new ObjectMapper();
String test = "{\n" +
" \"emailAddress\": \"Trest22#gmail.com\",\n" +
" \"loginName\": \"Testinguser222\",\n" +
" \"firstName\": \"Test222\",\n" +
" \"surName\": \"Test22\",\n" +
" \"primaryPhone\": \"\",\n" +
" \"companyId\": 123445,\n" +
" \"extracompanies\": \"[12311,33333]\",\n" +
" \"middleName\": \"Test\",\n" +
" \"mobilePhone\": 6666666666,\n" +
" \"fax\": 87687687686\n" +
" \n" +
" }";
Map<String, Object> maps = mapper.readValue(test, Map.class);
List<Map<String,Object>> converted = maps.keySet().stream().map(key -> {
Map<String,Object> internalMap = new HashMap<>();
internalMap.put("name", key);
internalMap.put("value", maps.get(key));
return internalMap;
}).collect(Collectors.toList());
String json = mapper.writeValueAsString(converted);
Output
[{"name":"emailAddress","value":"Trest22#gmail.com"},{"name":"loginName","value":"Testinguser222"},{"name":"firstName","value":"Test222"},{"name":"surName","value":"Test22"},{"name":"primaryPhone","value":""},{"name":"companyId","value":123445},{"name":"extracompanies","value":"[12311,33333]"},{"name":"middleName","value":"Test"},{"name":"mobilePhone","value":6666666666},{"name":"fax","value":87687687686}]

How to go on about receiving JSON array in flutter and parsing it?

I am trying to get a JSON array from a webservice URL and parse it in JSON. The thing is the tutorial I was following shows receving one JSOn obj and parsing it but I need to know how to receive a JSON array and parse it. Below is the code I am working on, I am stuck.
Model
class Fact {
int id;
int fact_id;
String fact;
String image;
String reference;
Fact(this.id, this.fact_id, this.fact, this.image, this.reference);
Fact.fromJson(Map<String, dynamic> json)
: id = json['id'],
fact_id = json['fact_id'],
fact = json['fact'],
image = json['image'],
reference = json['reference'];
Map<String, dynamic> toJson() =>
{
'id' : id,
'fact_id': fact_id,
'fact': fact,
'image': image,
'reference': reference,
};
}
I don't get how to write this for the array of facts which I am getting from the webservice.
Fact Download Manager
class FactsManager {
var constants = Constants();
fetchFacts() {
final lastFactId = 0;
var fetchRequestUrl = constants.fetch_facts_url;
if (lastFactId == 0) {
fetchRequestUrl = fetchRequestUrl + "?count=" + constants.firstTimePostCount.toString();
} else {
fetchRequestUrl = fetchRequestUrl + "?count=" + constants.firstTimePostCount.toString() + "&last_id=" + lastFactId.toString();
}
Future<List<Fact>> fetchPost() async {
final response = await http.get(fetchRequestUrl);
if (response.statusCode == 200) {
return List<Fact>
}
}
}
}
Example Data which I am trying to parse.
[
{
"id": "407",
"fact": "Monsanto once tried to genetically engineer blue cotton, to produce denim without the use of dyes, reducing the pollution involved in the dyeing process. ",
"reference": null,
"image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact492.png",
"fact_id": "1"
},
{
"id": "560",
"fact": "You can count from zero to nine hundred ninety-nine without ever having to use the letter \"a\" ",
"reference": null,
"image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact04.png",
"fact_id": "2"
},
{
"id": "564",
"fact": "In order to keep the project a secret, the British army used the innocuous name \"mobile water carriers\" for a motorized weapons project - which is the reason we call them \"tanks\". ",
"reference": null,
"image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact116.png",
"fact_id": "3"
},
{
"id": "562",
"fact": "In 2010 the mummified corpse of Sogen Kato, thought to be Tokyo's oldest man, was found in his bedroom by government officials. He had actually died in 1978. ",
"reference": null,
"image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact216.png",
"fact_id": "4"
},
{
"id": "566",
"fact": "In 1927 the US Supreme Court ruled it constitutional for the government to forcefully sterilize mentally handicapped people ",
"reference": null,
"image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact316.png",
"fact_id": "5"
}
]
You can do the following:
String receivedJson = "... Your JSON string ....";
List<dynamic> list = json.decode(receivedJson);
Fact fact = Fact.fromJson(list[0]);
In any case, you must consider the following in your json string and the Fact class that you have crafted:
In the json string the id and fact_id are Strings and you treat them as int. Either you change the json or the Fact class
Some strings inside the json string produce errors as the have additional quotation marks and this confuses the decoder.
A json string the works is the following:
String receivedJson = """
[
{
"id": 407,
"fact": "Monsanto once tried to genetically engineer blue cotton, to produce denim without the use of dyes, reducing the pollution involved in the dyeing process. ",
"reference": null,
"image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact492.png",
"fact_id": 1
}
]
""";
Easily
String arrayText = '[{"name": "dart1","quantity": 12 },{"name": "flutter2","quantity": 25 }]';
var tagsJson = jsonDecode(arrayText);
List<dynamic> tags = tagsJson != null ? List.from(tagsJson) : null;
print(">> " + tags[0]["name"]);
print(">> " + tags[1]["name"]);
print(">> " + tags[0]["quantity"].toString());
print(">> " + tags[1]["quantity"].toString());
output
2021-04-28 18:55:28.921 22085-22225/com.example.flutter_applicationdemo08 I/flutter: >> dart1
2021-04-28 18:55:28.921 22085-22225/com.example.flutter_applicationdemo08 I/flutter: >> flutter2
2021-04-28 18:55:28.921 22085-22225/com.example.flutter_applicationdemo08 I/flutter: >> 12
2021-04-28 18:55:28.921 22085-22225/com.example.flutter_applicationdemo08 I/flutter: >> 25

DocumentDB: bulkImport Stored Proc - Getting 400 Error on Array/JSON issue

I'm simply trying to execute the standard example bulkImport sproc for documentDB API and I can't seem to pass it an array of objects. I always get 400 errors despite the documentation giving clear direction to send an array of objects
.. very frustrating.
Additional details: Even if I wrap the array in an object with the array under a property of 'items' and include it in my sproc it still errors out saying the same bad request, needs to be an object or JSON-serialized. When I try to do JSON.stringify(docs) before sending it fails to parse on the other side.
Bad Request: The document body must be an object or a string representing a JSON-serialized object.
bulkInsert.js:
https://github.com/Azure/azure-documentdb-js-server/blob/master/samples/stored-procedures/BulkImport.js
My Code (using documentdb-util for async):
execProc(docs, insertProc);
async function execProc(docs, insertProc){
let database = await dbUtil.database('test');
let collection = await dbUtil.collection(database, 'test');
let procInstance = await dbUtil.storedProcedure(collection, insertProc);
try{
let result = await dbUtil.executeStoredProcedure(procInstance, docs);
console.log(result);
} catch(e){
console.log(e.body)
}
}
Header
Object {Cache-Control: "no-cache", x-ms-version: "2017-11-15",
User-Agent: "win32/10.0.16299 Nodejs/v8.9.0 documentdb-nodejs-s…",
x-ms-date: "Mon, 11 Dec 2017 07:32:29 GMT",
Accept:"application/json"
authorization: myauth
Cache-Control:"no-cache"
Content-Type:"application/json"
User-Agent:"win32/10.0.16299 Nodejs/v8.9.0 documentdb-nodejs-sdk/1.14.1"
x-ms-date:"Mon, 11 Dec 2017 07:32:29 GMT"
x-ms-version:"2017-11-15"
Path
"/dbs/myDB/colls/myColl/sprocs/myBulkInsert"
Params
Array(3) [Object, Object, Object]
length:3
0:Object {id: "0001", type: "donut", name: "Cake", …}
1:Object {id: "0002", type: "donut", name: "Raised", …}
2:Object {id: "0003", type: "donut", name: "Old Fashioned", …}
[{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.35
},
{
"id": "0003",
"type": "donut",
"name": "Old Fashioned",
"ppu": 0.25
}]
The "docs" must be an array of array of params, otherwise, the procedure executor will treat them as multiple params of the procedure, not a single-array-param.
the following code works when call storedProcedure to pass argument with array type.
JS:
var docs = [{'id':1},{'id':2}];
executeStoredProcedure(proc, [docs])
C#
var docs = new[] {new MyDoc{id=1, source="abc"}, new MyDoc{id=2, source="abc"}];
dynamic[] args = new dynamic[] {docs};
ExecuteStoredProcedureAsync<int>(
procLink,
new RequestOptions {PartitionKey = new PartitionKey("abc")},
args);
NOTE: you must ensure the 'docs' have the same partition key, and pass partion key in RequestionOptions
I had the same problem. I was able to get it to work by Stringify the Array and parse it in the stored procedure. I opened an issue on the github where that code originated as well. Below is what worked for me. Good luck.
---- Stringify Array
var testArr = []
for (var i = 0; i < 50; i++) {
testArr.push({
"id": "test" + i
})
}
var testArrStr = JSON.stringify(testArr)
//pass testArrStr to stored procedure and parse in stored procedure
---- Slightly altered original BulkImport
exports.storedProcedure = {
id: "bulkImportArray",
serverScript:function bulkImportArray(docs) {
var context = getContext();
var collection = context.getCollection();
var docsToCreate = JSON.parse(docs)
var count = 0;
var docsLength = docsToCreate.length;
if (docsLength == 0) {
getContext().getResponse().setBody(0);
}
var totals = ""
function insertDoc(){
var msg = " count=" + count+" docsLength=" +docsLength + " typeof docsToCreate[]=" + typeof docsToCreate+ " length =" + docsToCreate.length
if(typeof docsToCreate[count] != 'undefined' ) {
collection.createDocument(collection.getSelfLink(),
docsToCreate[count],
function (err, documentCreated) {
if (err){
// throw new Error('Error' + err.message);
getContext().getResponse().setBody(count + " : " + err);
}else{
if (count < docsLength -1) {
count++;
insertDoc();
getContext().getResponse().setBody(msg);
} else {
getContext().getResponse().setBody(msg);
}
}
});
}else{
getContext().getResponse().setBody(msg);
}
}
insertDoc()
}
}
If you want to test it in the portal Script Explorer I had to create an escaped string i.e.
var testArr = []
for(var i=200; i<250; i++){
testArr.push({"id":"test"+i})
}
var testArrStr = JSON.stringify(testArr)
console.log('"'+testArrStr.replace(/\"/g,'\\"') + '"')

Some JSON objects is undefined

So I'm working a bit with nodeJS and Steam API to try and make a trade bot
I need to know what items was recieved, but when I do I get
undefined
Here's the JSON:
{
"partner":{
"universe":1,
"type":1,
"instance":1,
"accountid":369917733
},
"id":"2112720622",
"message":"No need to accept, just testing out a bot.",
"state":3,
"itemsToGive":[
],
"itemsToReceive":[
{
"appid":730,
"contextid":"2",
"assetid":"10168993563",
"classid":"1989300153",
"instanceid":"302028390",
"amount":1,
"missing":true,
"icon_url":"IzMF03bi9WpSBq-S-ekoE33L-iLqGFHVaU25ZzQNQcXdB2ozio1RrlIWFK3UfvMYB8UsvjiMXojflsZalyxSh31CIyHz2GZ-KuFpPsrTzBG0qe6yD3n-ZDLdYXKOTVxqTudcPGjZrGLx5ujCF2nASeh-EF9XdfEAo2JLNZiKahtv0oMVu2u_0UdyEhk6f9BKZAarxm1OMLh9m3IWGBD1M58",
"icon_url_large":"IzMF03bi9WpSBq-S-ekoE33L-iLqGFHVaU25ZzQNQcXdB2ozio1RrlIWFK3UfvMYB8UsvjiMXojflsZalyxSh31CIyHz2GZ-KuFpPsrTzBG0qe6yD3n-ZDLdEC3YDlltU-cLND7c92Hxt-SVFGqfFe54SgACdfcFoDJPP82AOBtrhdZZ-Ga9zhwzDhgvNMZJfACpx2EfJbQ1xDhPJM5amiekAf1NktA",
"icon_drag_url":"",
"name":"Sealed Graffiti | Still Happy (Desert Amber)",
"market_hash_name":"Sealed Graffiti | Still Happy (Desert Amber)",
"market_name":"Sealed Graffiti | Still Happy (Desert Amber)",
"name_color":"D2D2D2",
"background_color":"",
"type":"Base Grade Graffiti",
"tradable":true,
"marketable":true,
"commodity":true,
"market_tradable_restriction":7,
"fraudwarnings":[
],
"descriptions":[
{
"type":"html",
"value":"This is a sealed container of a graffiti pattern. Once this graffiti pattern is unsealed, it will provide you with enough charges to apply the graffiti pattern <b>50</b> times to the in-game world.",
"app_data":""
},
{
"type":"html",
"value":" ",
"app_data":""
},
{
"type":"html",
"value":"",
"color":"00a000",
"app_data":{
"limited":"1"
}
}
],
"owner_descriptions":[
],
"actions":[
{
"name":"Inspect in Game...",
"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D9253357711394385702"
}
],
"market_actions":{
"0":{
"name":"Inspect in Game...",
"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D9253357711394385702"
}
},
"tags":[
{
"internal_name":"CSGO_Type_Spray",
"name":"Graffiti",
"category":"Type",
"category_name":"Type"
},
{
"internal_name":"normal",
"name":"Normal",
"category":"Quality",
"category_name":"Category"
},
{
"internal_name":"Rarity_Common",
"name":"Base Grade",
"category":"Rarity",
"color":"b0c3d9",
"category_name":"Quality"
},
{
"internal_name":"Tint5",
"name":"Desert Amber",
"category":"SprayColorCategory",
"category_name":"Graffiti Color"
}
],
"id":"10168993563",
"owner_actions":[
],
"market_marketable_restriction":0
}
],
"isOurOffer":true,
"created":"2017-05-13T09:50:24.000Z",
"updated":"2017-05-13T09:50:48.000Z",
"expires":"2017-05-27T09:50:24.000Z",
"tradeID":"1915564581201455085",
"fromRealTimeTrade":false,
"confirmationMethod":0,
"escrowEnds":null,
"rawJson":"{\n\t\"tradeofferid\": \"2112720622\",\n\t\"accountid_other\": 369917733,\n\t\"message\": \"No need to accept, just testing out a bot.\",\n\t\"expiration_time\": 1495878624,\n\t\"trade_offer_state\": 3,\n\t\"items_to_receive\": [\n\t\t{\n\t\t\t\"appid\": \"730\",\n\t\t\t\"contextid\": \"2\",\n\t\t\t\"assetid\": \"10168993563\",\n\t\t\t\"classid\": \"1989300153\",\n\t\t\t\"instanceid\": \"302028390\",\n\t\t\t\"amount\": \"1\",\n\t\t\t\"missing\": true\n\t\t}\n\t],\n\t\"is_our_offer\": true,\n\t\"time_created\": 1494669024,\n\t\"time_updated\": 1494669048,\n\t\"tradeid\": \"1915564581201455085\",\n\t\"from_real_time_trade\": false,\n\t\"escrow_end_date\": 0,\n\t\"confirmation_method\": 0\n}"
}
I can easily get partner, id, message, state, isOurOffer and all the time things, but when I try to get itemsToRecieve, it just throws undefined
The JSON is gathered through an event and the above is the exact JSON that I recieved
This is the event:
manager.on('sentOfferChanged', function(offer, oldState) {
var state = offer.state;
if(state == 3) {
console.log("Offer " + offer.id + " was accepted");
console.log("[Offer #" + offer.id + "] The following items was recieved: ");
console.log(offer.itemsToReceive);
}
});
Why would it do that for only one of the objects?
Maybe you can use a for to log each item of itemToReceive.
Something like this:
manager.on('sentOfferChanged', function(offer, oldState) {
var state = offer.state;
if(state == 3) {
console.log("Offer " + offer.id + " was accepted");
console.log("[Offer #" + offer.id + "] The following items was recieved: ");
for(var i in itemstoReceive)
{
var name = itemsToReceive[i].name;
console.log(name);
}}
});

JSON.net parsing of dynamic JSON

I have JSON that looks like this:
{
"status": {
"code": 0,
"message": "OK"
},
"data": {
"_idtype": "cusip",
"_id": "00768Y883",
"api": {
"_name": "PortfolioBreakdownsRaw",
"PortfolioDate": "2015-10-12",
"GlobalBondSuperSectorLongSalePositionBreakdown": [
{
"Name": "Municipal",
"Value": "0.57842"
},
{
"Name": "Corporate",
"Value": "1.79649"
},
{
"Name": "Securitized",
"Value": "5.29493"
},
{
"Name": "Cash & Equivalents",
"Value": "166.20776"
}
],
"GlobalBondSuperSectorShortSalePositionBreakdown": [
{
"Name": "Government",
"Value": "0.90557"
}
]
}
}
}
I am able to get the api portion of the response easily:
var jObject = JObject.Parse(json);
var api = jObject["data"]["api"];
From here, I don't what if any arrays will be included in the response. The ultimate goal will be to create a parser that will be able to get the array names (GlobalBondSuperSectorShortSalePositionBreakdown) and as many rows of key-value pairs that it may contain, without first knowing the names such as (GlobalBondSuperSectorShortSalePositionBreakdown) beforehand.
I can't seem to find a good way to loop through the object, determine there are arrays at the api level and then iterate through those to get the values.
Any help would be appreciated.
Here's an example. In this code, the api variable holds a JObject, so we can iterate over its properties. From there, we look at the Type of each property value to see if it is an array or not. If it is, then we can iterate over that array to get the JObjects within it, and extract the Name and Value values that we expect to find there. Does this help?
var jObject = JObject.Parse(json);
var api = jObject["data"]["api"];
foreach (JProperty prop in api.Children<JProperty>())
{
JToken value = prop.Value;
if (value.Type == JTokenType.Array)
{
Console.WriteLine(prop.Name + ": ");
foreach (JObject jo in value.Children<JObject>())
{
Console.WriteLine(" " + jo["Name"] + ": " + jo["Value"]);
}
}
else
{
Console.WriteLine(prop.Name + ": " + value);
}
}
Output:
_name: PortfolioBreakdownsRaw
PortfolioDate: 2015-10-12
GlobalBondSuperSectorLongSalePositionBreakdown:
Municipal: 0.57842
Corporate: 1.79649
Securitized: 5.29493
Cash & Equivalents: 166.20776
GlobalBondSuperSectorShortSalePositionBreakdown:
Government: 0.90557
Fiddle: https://dotnetfiddle.net/XyoXQy
With Linq you can play pretty nice with Json.net:
Here is an easily readable version of the chunk of code that will create two dictionaries out of the JArray properties under the api element:
var api = jObject["data"]["api"];
var arrays = api.Cast<JProperty>().Where(o => o.Value.Type == JTokenType.Array).Select(token => token.Value).ToArray();
var dictionaries = new List<Dictionary<string, string>>();
foreach (var array in arrays)
{
var dictionary = array.ToDictionary(token => token["Name"].Value<string>(), token => token["Value"].Value<string>());
dictionaries.Add(dictionary);
}
alternative:
The same thing, but a shorter, more compact version :
var api = jObject["data"]["api"];
var dictionaries = api
.Cast<JProperty>()
.Where(o => o.Value.Type == JTokenType.Array)
.Select(token => token.Value)
.Select(array => array.ToDictionary(token => token["Name"].Value<string>(), token => token["Value"].Value<string>()));