Can i return an array of "number, number" in json format? - arrays

i have a list of lat/long objects on my server.
eg.
public class LatitudeLongitude
{
public float Latitude;
public float Longitude;
}
simple.
now, can i return a collection of these, in json format .. BUT ... i do not want to list the key, just the values.
This means the normal result would be something like ...
{ { lat: 111, long : 222 }, { lat: 333, long : 444 } } ..
but i'm hoping for...
{ {111, 222}, {333, 444} ..... }
{ {obj1.Lat, obj1.Long}, {obj2.Lat, obj2.Long} ... etc. ... }
Is this possible? I mean, i can make that string on the server side easily. But is that a correct JSON output format?
Can someone please confirm, etc.
cheers :)
PS. I hardly know any Json, so please don't hesitate to correct my poor examples above.

Use JSON arrays:
[ [111, 222], [333, 444], ... ]

Ayman's proposal isn't quite correct JSON syntax. As an object {..} is always composed of fields having a name. So we again would have object with 2 fields of type 'array' that don't have a name -> not valid json for an object.
There is a very good description of how a json string can look like at www.json.org. Looking at this description you'll see an object is not allowed without a name String for a field so this {111,222} is not a valid object in json, but this is valid [111,222] array. This is not a valid object {[111,222]} but this is {array1 : [111,222]}.
I guess what you actually want is most likely an array of arrays like this not encapsulated as an object.
[[111,222],[333,444]].
This approach would give you the choice to add as much arrays of lat/long as you like to the enclosing array and at the same time you can process the inner arrays no matter what size the outer array is with an javascript loop.
Hope that helped.
cheers
Michael

If you need to access it using the keys in JSON, you'll need to specify it (or use a JS to convert arrays to objects on the client side). Otherwise, arrays should work:
var json = [ [123, 456], [234, 567] ];
var convertedJson = [];
for (i = 0; i < json.length; ++i) {
var thisObj = new Object();
thisObj.latitude = json[i][0];
thisObj.longitude = json[i][1];
convertedJson[i] = thisObj;
}

But is that a correct JSON output
format?
You can paste in JSON at jslint.com to validate your JSON

The ASP.NET MVC JSON serializer should convert a IList<LatitudeLongitude> to something like this:
[{"Latitude":111,"Longitude":222},{"Latitude":333,"Longitude":444} .. ]
I believe that under the ASP.NET MVC JSON serializer is just a hot-wired .NET core Javascript serializer.
I dont think it's possible from .NET using a serializer. Prob need to render the string manually.

Related

How do we compare the value in RealmSwift List and Json nested Array?

Realmswift Data Model
class User {
let id = RealmOptional<Int>()
dynamic var name = ""
let albums = List<Album>()
override static func primaryKey() -> String {
return "id"
}
}
class Album: Object {
dynamic albumName = ""
let imageIDs = List<ImageID>()
}
class ImageID: Object {
let imageId = RealmOptional<Int>()
}
JSON data
{
"10001": {
"id" : 10001,
"name": "John",
"album": {
"albums": [
{
"albumName": "Summer1999",
"imageIds": [11223, 11224, 11227]
},
{
"albumName": "Xmas1999",
"imageIds": [22991, 22997]
},
{
"albumName": "NewYear2000",
"imageIds": [5556, 776, 83224, 87543]
}
]
}
}
}
I have the above json data and I m using SwiftyJSON to parse the data then write into realm. Everything is working great except for checking and updating of data (for example imageIds on json file have changed).
Question: How do i compare the JSON arrays and RealmSwift List to determine it any updates need to be written into the database?
You can take advantage of your primary key here. As Realm Swift documentation states:
Creating and Updating Objects With Primary Keys: If your model class
includes a primary key, you can have Realm intelligently update or add
objects based off of their primary key values using
Realm().add(_:update:).
So (I assume that you get the JSON from some kind of a request (REST etc.) and then parse it with SwiftyJSON to create a 'User' object) you can treat the new 'User' object as regular new 'User' and try to add it to Realm as usual, but 'update' parameter must be 'true'. If there already was a user with the id of the 'User' object you are trying to add, it will just update the existing 'User' i.e. changing its modified values from the new 'User' created by parsing new JSON data. This might look something like this:
//Parse JSON and create a 'User'
let newUserFromJSON = parseAndCreateUserFromJSON(JSONData)
let realm = try! Realm()
do {
try realm.write {
realm.add(newUserFromJSON, update: true)
}
} catch let error as NSError {
print("error writing to realm: \(error.description) & \(error)")
} catch {
print("error writing to realm: UNKNOWN ERROR")
}
I'm afraid there's probably no easy answer to this. There's no mechanism in Realm to compare the contents of a Realm Object to an external object to see if their data matches. You would need to iterate through each object in the Realm object and manually compare it.
This wouldn't be too much code to write (Since you can get a list of all of the Realm file's properties via the objectSchema property of Realm objects, and then use key-value coding to pull them out in a single for loop), but would still be a fair amount of overhead to perform the compare.
That being said, if what you're wanting to look at is just certain properties that might change (i.e. like you said, just the imageIDs property), then you could easily just check the values you need.
What bcamur has suggested is definitely the quickest (And usually preferred for JSON handing) solution here. As long as you've set your primary key properly, you can call Realm.add(_:, update:) with update set to true to update the object.
Please keep in mind this doesn't merge the new data with what was already in Realm; it'll completely overwrite the old object with the new values, which if it sounds like your ID numbers are changing, would be the best course of action.

Get each JSON array value using PHP

I've been trying to read this JSON with PHP:
{
"total_found":"49",
"1":{
"title":"Maze Runner-The Scorch Trials 2015 HD-TS x264-Garmin",
"category":"video",
"seeds":2141,
"leechs":1176,
"torrent_size":1122230176,
"torrent_hash":"29d3e7062825a62abdd877ee96dc3fea41183836"
},
"2":{
"title":"Maze.Runner-The.Scorch.Trials.2015.720P.HD-TS.x264.AC3.HQ.Hive-CM8",
"category":"hdrip",
"seeds":395,
"leechs":1856,
"torrent_size":3999751475,
"torrent_hash":"e1e14a5ccf540a739907db2e1e0d810ecdb8bebc"
}
}
How can I get each title and torrent_size?
The easiest thing to do is to decode the JSON to an array. PHP has a built-in function for this:
$results = json_decode($json_data);
http://php.net/manual/en/function.json-decode.php
To clearly see the array structure, try dumping the variable $results using print_r();, i.e.:
print_r($results);
Then you simply need to access the data using the array.
It will be something like $results[1]['torrent_size'];.

Pass an array of integers to ElasticSeach template

I am trying to pass an array of integers to ElasticSearch template using the below mustache template.
{{#filter5_terms}}
"terms": {
"{{filter5_name}}": [
"{{#filter5_lt}}",
"{{.}}",
"{{/filter5_lt}}" ]
}
{{/filter5_terms}}
Above works, If I pass a string array (Ex: ["A","B"]. But the same is failing with the int array [1,2] with Nested: NumberFormatException[For input string: ""]; error.
Reference: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html#_passing_an_array_of_strings
Can you please let me know if I am missing anything?
Thanks
Anil
You really shouldn't rely on that, as the format is an inner implementation of Mustache and thus, subject to change. For example, if you try to emulate that using mustache.js, you'll get something like:
"terms: {
"property": 3,4
}
To workaround this problem, you should add square brackets to the templated values. So, your example becomes:
"terms": {
"{{filter5_name}}": [{{filter5_lt}}]
}
And that will get you what you want.
At least, this is true in mustache.js 2.2.1
I did fix this.
We can use the below to replace the integer array into ElasticSearch query.
"terms": {
"{{filter5_name}}": {{filter5_lt}}
}
ElasticSearch documentation has an example to replace string arrays and I tried to use the same for integer arrays and it did not work.
So I had to use the above which is provided in Mustache templating examples.
Thanks
Anil

Extjs how to decode a json string?

I have to decode JSON with Extjs 4:
I have used Ext.decode(string, true), but it doesn't work 'cause my string is a JSON with a JSON string (escaped) inside... like this:
var string = '{
success: true,
rows: [{
"id": 33,
"defaultset": 1,
"name": "Generico",
"jsonfields": "[{\"name\":\"cm:addressees\",\"title\":\"Destinatari\",\"description\":\"Destinatari\",\"dataType\":\"d:text\",\"url\":\"\/api\/property\/cm_addressees\"}]",
"eliminato": 0
}]
}';
as you can see the field jsonfields is a JSON string. When I use
Ext.decode(string, true);
nothing happens neither error.
Any suggestions?
You may try like this:
var string = '{success:true, rows:[{"id":33,"defaultset":1,"name":"Generico","jsonfields":"[{\\"name\\":\\"cm:addressees\\",\\"title\\":\\"Destinatari\\",\\"description\\":\\"Destinatari\\",\\"dataType\\":\\"d:text\\",\\"url\\":\\"/api/property/cm_addressees\\"}]","eliminato":0}]}';
var decodedString = Ext.decode(string);
console.log(decodedString);
that's a little bit tricky. If you remove safe parameter you will see that your json misses \ in your jsonfields thats because your string is in ' quotes and one \ does the job for it but you want something different... so you have to double it.
fiddle example
It does work, for example I am getting my Json from the server,
websocket.onmessage = function(event)
from the websocket actually and later when I want to decode my json,
var json = Ext.decode(event.data);
and where I need my string for example
json.map.MessageType
My json looks like this:
mpty":false,"map":{"MessageText":"Ciao, how are you?","MessageType":"IN"},"hashtable":{"MessageText":"Ciao, how are you?","MessageType":"IN"},"persistData":{"MessageText":"Ciao, how are you?","MessageType":"IN"}}
Hope this helps, cheers!

Using CouchDB-lucene how can I index an array of objects (not values)

Hello everyone and thanks in advance for any ideas, suggestions or answers.
First, the environment: I am using CouchDB (currently developing on 1.0.2) and couchdb-lucene 0.7. Obviously, I am using couchdb-lucene ("c-l" hereafter) to provide full-text searching within couchdb.
Second, let me provide everyone with an example couchdb document:
{
"_id": "5580c781345e4c65b0e75a220232acf5",
"_rev": "2-bf2921c3173163a18dc1797d9a0c8364",
"$type": "resource",
"$versionids": [
"5580c781345e4c65b0e75a220232acf5-0",
"5580c781345e4c65b0e75a220232acf5-1"
],
"$usagerights": [
{
"group-administrators": 31
},
{
"group-users": 3
}
],
"$currentversionid": "5580c781345e4c65b0e75a220232acf5-1",
"$tags": [
"Tag1",
"Tag2"
],
"$created": "/Date(1314973405895-0500)/",
"$creator": "administrator",
"$modified": "/Date(1314973405895-0500)/",
"$modifier": "administrator",
"$checkedoutat": "/Date(1314975155766-0500)/",
"$checkedoutto": "administrator",
"$lastcommit": "/Date(1314973405895-0500)/",
"$lastcommitter": "administrator",
"$title": "Test resource"
}
Third, let me explain what I want to do. I am trying to figure out how to index the '$usagerights' property. I am using the word index very loosely because I really do not care about being able to search it, I simply want to 'store' it so that it is returned with the search results. Anyway, the property is an array of json objects. Now, these json objects that compose the array will always have a single json property.
Based on my understanding of couchdb-lucene, I need to reduce this array to a comma separated string. I would expect something like "group-administrators:31,group-users:3" to be a final output.
Thus, my question is essentially: How can I reduce the $usagerights json array above to a comma separated string of key:value pairs within the couchdb design document as used by couchdb-lucene?
A previous question I posted regarding indexing of tagging in a similar situation, provided for reference: How-to index arrays (tags) in CouchDB using couchdb-lucene
Finally, if you need any additional details, please just post a comment and I will provide it.
Maybe I am missing something, but the only difference I see from your previous question, is that you should iterate on the objects. Then the code should be:
function(doc) {
var result = new Document(), usage, right;
for(var i in doc.$usagerights) {
usage = doc.$usagerights[i];
for(right in usage) {
result.add(right + ":" + usage[right]);
}
}
return result;
}
There's no requirement to convert to a comma-separated list of values (I'd be intrigued to know where you picked up that idea).
If you simply want the $usagerights item returned with your results, do this;
ret.add(JSON.stringify(doc.$usagerights),
{"index":"no", "store":"yes", "field":"usagerights"});
Lucene stores strings, not JSON, so you'll need to JSON.parse the string on query.

Resources