w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Parsing an array of json objects to scala objects with pickling
"Collections of non-primitive types are not supported" (yet) https://github.com/scala/pickling/issues/6 From what I can see, scala.pickling is still very rough around the edges. Furthermore, the default pickling format JSONPickleFormat requires some meta-data (the tpe field) and I'm guessing won't be parsing arbitrary JSON objects.

Categories : Java

Jackson parsing JSON containing an array of objects and array of maps w/ dynamic keys
You could probably get around this by writing your own custom deserializer and register it with the object mapper that you are using. This should work as you will have complete control of how each object is deserialized into a User object. See this jackson documentation on how to roll your own deserializer. Would also like to say, if you have control over the json structure - I would change the key value (which I am guessing is an ID for the user) to be a part of the actual json object as opposed to being the key. This will help you avoid the issue all together. For example: "users":{ { "id":"1234", "firstname":"Joe", "lastname":"Smith" }, { "id":"9876", "firstname":"Bob", "lastname":"A

Categories : Java

how to filter json array by some condition
Try this.. then change zero1check datatype as int JSONArray school = json2.getJSONArray("data"); for (int i1 = 0; i1 < school.length(); i1++) { JSONObject object = school.getJSONObject(i1); if(zero1check == 0) { if(object.getString("id").equals("m1")) { Category_name.add(object.getString("dish_name")); } } else if(zero1check == 1) { if(object.getString("id").equals("m2")) { Category_name.add(object.getString("dish_name

Categories : Android

SELECT or Filter from JSON(?) Array
A good option would be to use ScriptDb Services, but if the amount of data is great, you'll run faster with the problems of the limits of the quotas of service. From your example, the following works: var json = JSON.parse('{"result": [{"id": 1, "value": "value1"}, {"id": 2, "value": "value2"}]}').result; var items = json.filter(function(item) { if(item.id === 2) { return item; } }); Logger.log(items);

Categories : Json

Deserializing JSON array containing objects with an array using GSON
You have a couple issues. First and foremost, what is causing the error you post is that you are telling Gson that your JSON represents an object (SearchResults) when it doesn't; your JSON is an array of objects (specifically, an object you're mapping to your Java Band class). The correct way to do this is via: Type collectionType = new TypeToken<Collection<Band>>(){}.getType(); Collection<Band> bands = gson.fromJson(jsonString, collectionType); Once you do that you're going to have a problem in that in your Java class you're saying that "Picture" in your JSON is an array of Photo objects when in fact it's not; it's a single object.

Categories : Json

Filter Array Before Push JSON Object to Javascript
This would check for previous value with the current value and skip it if they are same dataJSON2 = []; var lastVal = parsed2 && parsed2[0]; for (var i = 1; i < parsed2.length; i++) { if (lastVal !== parsed2[i].value) { dataJSON2.push([(parsed2[i].timestamp), parseFloat(parsed2[i].value)]); lastVal = parsed2[i]; } }

Categories : Javascript

Filter only in one element/array of Twitter JSON file
What are you using for your grep regex? If you are just using 'iphone' for the regex then yes, you'll get multiple hits. You can expand your regex to match iphone only in text section before the source: grep '"text":".*iphone.*","source":' myfile.txt will search for the pattern iphone after "text" but before "source". It will ignore iphone in the rest of the line.

Categories : Json

Filter Object and Array from user input JSON text
This post might help you. It's a library that provides exceptionally fast JSON-parsing. Specifically, it provides functionality which wraps JsonTextReader and pumps the results into a Dictionary that you can easily read from, ignoring the JSON tags that your sample application outputs.

Categories : C#

Slicing a JSON array to get first five objects
The code you posted works fine! Here is a demo: http://jsfiddle.net/enXcn/1/ Note how, when you are changeing the value of slice, more or less elements are displayed, which is what you discribed it should do. HTML: <div id="recentActivities"></div> JS: var recentActdata = [ { "displayValue":"Updated Guidelines", "link":"#", "timestamp":"29/06/2013 01:32" }, { "displayValue":"Logging", "link":"#", "timestamp":"28/06/2013 16:19" }, { "displayValue":"Subscribe", "link":"#", "timestamp":"21/06/2013 14:30" }, { "displayValue":"Artifactory Vs Nexus", "link":"#", "timestamp":"21/06/2013 13:39" }, { "displayValue":"CTT - Java 7", "link":"#", "timestamp":"20/06/2013 13:30" }, { "displayValue":"Added Art

Categories : Javascript

Create an array of JSON Objects
Small mistake try { for (int i = 0; i < orderList.size(); i++) { JSONObject json = new JSONObject(); // update here json.put("orderno", orderList.get(i).getOrderNumber() .toString()); json.put("tableno", orderList.get(i).getTableNumber() .toString()); json.put("itemname", orderList.get(i).getItemName().toString()); json.put("amount", orderList.get(i).getAmount().toString()); json.put("ordstatus", orderList.get(i).getOrderStatus() .toString()); array.put(json); } catch (JSONException je) { return false; }

Categories : Android

PHP: Give a name to an array of JSON objects?
Try this: <?php $kitty = array('kitten' => array()); $kitty['kitty'][] = array('kitty' => 'Tabby'); $kitty['kitty'][] = array('kitty' => 'Ruby'); $kitty['kitty'][] = array('kitty' => 'Silver'); var_dump($kitty); var_dump(json_encode($kitty)); which results in: {"kitty":[{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]}

Categories : PHP

json object vs array of objects
The best way to handle this situation is to change your JSON response so that meeting is always an array, even if it only has one entry. If you aren't able to update the way the JSON is being created, a simple way is to test using instanceof: if(results.meeting instanceof Array) { //array } else { //object }

Categories : Javascript

parsing of json array objects
I'll throw you a bone. When you find a sigil representing the beginning of an element in the text, call a function that knows how to handle that type of element - hash, array, string, number, etc (http://www.json.org/). Now how you want to handle things like a hash is up to you, and C makes it a bit difficult to store the different types of values easily, but basically in each section, you return the object representing that and it gets turned into a overall data structure representing the json you just parsed. VERY pseudocode: parseJson(char* json) { if json[0]=='[' parseJsonArray(json+1) if json[0]=='{] parseJsonArray(json+1) if json[0]=='"' parseJsonString(json+1) ...etc... } parseJsonArray(char* json) { SomeSortOfList array = MakeListThing(); while *json !

Categories : C

PHP - How to add more objects to JSON Encoded Array
The simplest solution would be using substr $json = '[{"city":"Asasqewq"},{"city":"New Brunswick"},{"city":"Jersey City"},{"city":"Summit"},{"city":"Edison"},{"city":"Hillside"},{"city":"East Orange"}]'; $new = '{"city":"New City 1"},{"city":"New City 2"}'; $json = substr($json,0,-1) . ',' . $new . ']';

Categories : PHP

Parsing an array of JSON objects using Jackson 2.0
You can simply call the JsonNode.traverse() method to get the JsonParser. Tested with the following simple example: public class App { public static class Foo { public int foo; } public static void main(String[] args) { String json = "{"someArray":[{"foo":5},{"foo":6},{"foo":7}]}"; ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(json); node = node.get("someArray"); TypeReference<List<Foo>> typeRef = new TypeReference<List<Foo>>(){}; List<Foo> list = mapper.readValue(node.traverse(), typeRef); for (Foo f : list) { System.out.println(f.foo); }     } } outputs: 567

Categories : Android

Loop and create a Array from JSON Objects
Why not rename fileid to file and make fileid a field within that array? (like fileid: <fileid>) Or can´t you change the incoming JSON-String?

Categories : Android

How to POST a JSON request containing an array of objects?
Yes you can send multipart/mixed through JQuery ajax, but must add extra stuff: cache: false, contentType: false, processData: false, $.ajax({ url: 'php/test.php', data: {name: "test1", age 5}, cache: false, contentType: false, processData: false, type: 'POST', success: function(data){ alert(data); } });

Categories : Ajax

Iterating over objects in a JSON array with JavaScript
for( var i = 0; i < sponsors.length; i++) { var sponsor = sponsors[i]; console.log(sponsor.name); } Using a standard for loop will work well, providing you know the key names for the data!

Categories : Javascript

Loop through json array of objects issue
i hope this could be helpful to you try to type cast with object foreach ($json_output->dataObjects as $objects){ let me know if i can help you more

Categories : PHP

Sorting Array of JSON Objects with angularJS
You could use the "filter" filter: <div ng-repeat="month in months"> <h3>{{month}}</h3> <ul ng-repeat="entry in entries | filter:{date:month}"> {{entry.text}} </ul> </div> You'll need to do some manipulation of the date property to compare to the month.

Categories : Angularjs

Combining Nested Objects in a JSON Array
You have to write function to merge array of objects under key and then get map values. Here it is: Merge function: function mergeArray(array) { var merged = {}; $.each(array, function() { var item = this; // Use name as a key if (typeof merged[item.name] != 'undefined') { // merge values array $.merge(merged[item.name].values, item.values); } else { merged[item.name] = item; } }); // get values from { key1: value1, key2: value2, ... } object return getObjectValues(merged); } Getting values from object: function getObjectValues(obj) { var values = []; $.each(obj, function(key,valueObj){ values.push(valueObj); }); return values; } Here is working example.

Categories : Javascript

Traversing an array of objects from JSON using Boost
If you google it, you can find several results: property_tree JSON parser using above example using JSON parser Update Try this : BOOST_FOREACH(const ptree::value_type& child, node.get_child("life.fungi")) { std::cout << child.second.get<std::string>("sporeMass") << " "; }

Categories : Json

Append array data as objects to json file
What you can do is decode json and then merge them. $data = json_decode(file_get_contents(./images_list.json)); $result = array_merge((array)$data, (array)$newImage); and then just output json_encode file_put_contents('./images_list.json', json_encode($result, JSON_FORCE_OBJECT));

Categories : PHP

Convert String to Array of JSON Objects (Node.js)
How about this: var obj = JSON.parse("{"items":" + request.param('items') + "}"); obj.title = request.param('title'); obj.thumb = request.param('thumb'); JSON.stringify(obj);

Categories : Javascript

How to convert JSON object array from Meteor Collection API into iOS objects?
Have you tried this? NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding]; NSArray* json = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil]; if (!json) { NSLog(@"Error parsing JSON: %@", e); } else { for(NSDictionary *item in json) { NSLog(@"Item: %@", item); } } And then loop through the array to strongly type your objects. Or you can use one of the many open source JSON parses available: https://github.com/icanzilb/JSONModel for example.

Categories : IOS

How to access multiple json objects send in array django
While this is very old I found myself searching for this exact problem... I found a way that works although I feel it is a bit unreliable Javascript: var rows = []; $('.some_class').each(function(){ var id = $(this).attr('data-id'); var something = $(this).attr('data-something'); var item = {}; item["id"] = id; item["something"] = something; rows.push(JSON.stringify(item)); }); arr = rows.join("/"); ajax_req = $.ajax({ url: '../some_url/', type: "POST", data: {req_arr : arr}, }); views.py items = request.POST.get('req_arr', None) items = str(items).split("/") for i in range(0, len(items)): item = json.loads(items[i]) id = item['id'] something = item['something']

Categories : Javascript

How can I access the images in an Instagram JSON? Use objects or an associative array?
To access infos from StdClass you can do this: foreach($data->images as $i){ $i->url; } You can force a casting to array too: foreach($data->images as $i){ $i = $i->toArray(); $i['url']; } And you can get the json decode on array form: $data = json_decode($json,true); //the second param true means, bring me it like array.

Categories : PHP

Android json objects to array list in Parcelable class
You can use droidQuery to simplify JSON parsing. To convert your JSONObject to a Key-Value mapping, you can use this: List<String> items = new ArrayList<String>();//this will contain your JSONObject strings Map<String, ?> data = null; try { JSONObject json;//this references your JSONObject data = $.map(json); } catch (Throwable t) { Log.e("JSON", "Malformed JSON Object"); } Then, to loop through each element, just do this: if (data != null) { for (Map.Entry<String, ?> entry : data.entrySet()) { items.add(entry.value().toString()); } } Now your List items is populated with the String representation of your JSONObejcts. Later, if you want to parse this JSON, just do: int index = 2;//the index of the JSONObject you want try { Map

Categories : Android

Jackson JSON: Serialize Array of Objects as their parent type
You should use the @JsonSerialize annotation. It will allow you to specify a Typing value as either dynamic or static. In your case you want to use the static type rather than waiting til runtime for it to see the specific subclass.

Categories : Java

How to access JSON array of objects, returned by PHP PDO, inside javascript/jQuery?
If it's in a separate PHP file then AJAX seems like the best choice. Take a look at the documentation for the jQuery.getJSON() wrapper function. Basic usage would look something like this: $(document).ready(function() { // on page load $.getJSON('yourpage.php', function(data) { // data is your array // use it to create your widget in here }); });

Categories : Jquery

Jackson and REST Android Annotations: Deserialize JSON Array of Objects
I think I misunderstood the example at https://github.com/excilys/androidannotations/wiki/Rest-API#get. I think the array still must be wrapped inside a JSON object in that example (It'd be nice if they included example JSON data). The data the service I'm connecting to does not return an object wrapping the array like that, so, I altered the REST client to look like this: @Rest(rootUrl = Constants.ApiConfig.API_ROOT, converters = {MappingJackson2HttpMessageConverter.class}) public interface RestApiClient { @Get("/bookmark/read?id={identifier}") public ArrayNode getBookmarks(String identifier); } And I wrote a method in another class to iterate the ArrayNode and build the bookmarks: public List<Bookmark> getBookmarks(Content content) { ArrayList<Bookmark> book

Categories : Rest

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type with complex and nested objects
According to your JSON data, the objects that you need to map to have to look like this (unless you have your own JsonDeserializer of course): public class Banner { public string LocationCodeString { get; set; } public int LocationCodeInt { get; set; } public string MediaUrl { get; set; } } public class CampaignWithChosenProposal { public List<Banner> Banners { get; set; } public string Code { get; set; } public string CustomerInstruction { get; set; } public string InfoLink { get; set; } public string LobbySubTitle { get; set; } public string LobbyTitle { get; set; } public string MoreText { get; set; } public int NumOfColumns { get; set; } public int NumOfRows { get; set; } public string OriginString { get; set; } public int

Categories : C#

How to send an array of strings in JSON to create multiple objects in Rails?
Base64 is a red-herring (something that can confuse an argument) so let's put that aside for a minute. JSON is capable of representing an array, so that's the place to start, because you want two of something. Pretending that we're doing what JavaScript and the browser would do is easy: require 'json' ary = ['content for box one', 'content for box two'] puts JSON[ary] # >> ["content for box one","content for box two"] At this point we have the same sort of base string that JavaScript would create for an array containing two ASCII strings. For this part of the test, it's inconsequential whether it's ASCII or binary. Note that JSON left the content of the strings in the array alone. We can use the BASE64 encoding inside those strings and know that JSON will leave it alone: puts

Categories : Ruby On Rails

Alternative to creating large client side Javascript array of objects via JSON file?
If your server responds quickly In this case, you can probably simply load data on demand when a user clicks. The server is quick, so why bother trying to be smarter for no gain. If the server is quick, but not quick enough, then you might be able to preload the next level while drawing the first. Eg if you have just rendered the graph at the "office" level, then silently preload the "manager" next level down data while the user is still reacting to the screen update. If the server is too slow for data on demand In this case you probably need to model exactly where it is slow and address that. There are several things in play here and your question doesnt exactly say. Is the server slow to query the database, if yes fix it. There is little you can do client side to solve this. Is th

Categories : Javascript

Using JQuery/JavaScript how would I group values in an array of objects and create a new array of objects from the groups
If you're willing to use Underscore.js, this becomes pretty trivial. Assuming data is your original list of json objects, this will achieve what you're after: var groups = []; var by_grade = _.groupBy(data, function(obj) { return obj['grade'] }); _.each(by_grade, function(objs, grade) { var group = {}; group['grade'] = grade; group['ids'] = _.pluck(objs, 'id'); group['versions'] = _.pluck(objs, 'version'); // Use the following if the value is known to be // the same for all grouped objects group['platform'] = objs[0]['platform']; // And the rest... groups.push(group); }); _.groupBy() will group your objects by grade, resulting in two objects with the keys X and A, whose values are lists of objects with the corresponding grades. You can then loop ove

Categories : Javascript

python json.loads / json.load truncates nested json objects?
JSON doesn't care about the keys for objects, but the json.load and json.loads convert to a Python object using this conversion table. JSON objects are turned into python dict's, which means you can't have repeated keys.

Categories : Python

java method accepts array of objects and a double then returns an array of objects
You need to create the array before you write to it. House[] lowPriceHouses = null; should be something like House[] lowPriceHouses = new House[houses.length]; you actually want a smaller array since, you might not need all houses.. It would be easier to make this a ArrayList and then convert it toArray before returning. for (int i = 0; i <= houses.length; i++) You want to do only < This is because when you have an array of size 10, the elements are indexed from 0 - 9. Thus accessing the element arr[10] will lead to issues.

Categories : Java

How to use a case class to deserialize an array of json objects to List[Map[String,String]]
As I replied to you on the Salat mailing list, Salat doesn't support deserializing nested collections right now. https://github.com/novus/salat/wiki/Collections

Categories : Scala

converting multiple json objects into scala objects
Play's type class-based JSON library provides reader and writer instances for Seq[A] for any A with the appropriate instances, so all you have to do is provide a reader instance for your user type and you get a reader for a collection of users for free. We can start with the following case class (note that I've made the fact that the email address is optional explicit with Option): case class User(firstName: String, age: Double, email: Option[String]) Next we define our reader. I'm using 2.1's combinators, but there are other (more verbose) options. import play.api.libs.json._ import play.api.libs.functional.syntax._ implicit val userReads = ( (__ 'name).read[String] and (__ 'age).read[Double] and (__ 'email).read[Option[String]] )(User.apply _) We can test it: val userJs

Categories : Json

In a Javascript array of objects, how can I target a specific array element by name/ID if that element is an array of objects itself?
First off, comments should be an array and you have an object. Then proceed like this: reviews[someIndex].comments.push( { commenter: 'john', comment: 'hello!!'}); I.e. if you need to add a comment to the first post do: reviews[0].comments.push( { /* your comment */ } ); EDIT : I always used get() to retrieve an index but I seem to not be able to find much documentation about it, so I'm assuming (though I'm not sure) that [i] is a more standard way of doing things, hence why I changed the example. However the concept of pushing into comments doesn't change. EDIT 2: OP wants to target a particular element in an array. I would use Array.prototype.indexOf as described here where you can find a solution for browsers that do not support indexOf as well.

Categories : Javascript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.