Ruby: integrate a ruby key/value-hash in an existing JSON string - arrays

The JSON-String:
jsonString = {"string1" => {"test1" => "test2"}}
results (with JSON.pretty_generate) in a pretty printed:
{
"string1":
{
"test1": "test2"
}
}
But when I try to add all elements of two arrays into this JSON-String
keys = [:key0, :key1]
values = [:value0, :value1]
my_hash = Hash[keys.zip values]
jsonString = {"string1" => {"test1" => "test2", my_hash}}
I'm always getting a:
syntax error, unexpected '}', expecting =>
jsonString = {"string1" => {"test1" => "test2", my_hash}}
I would have expected a behavior like this:
jsonString = {"string1" => {"test1" => "test2", keys[0] => values[0], keys[1] => values[1]}}
Output:
{
"string1":
{
"test1": "test2",
"key0": "value0",
"key1": "value1"
}
}
Is there a way to this using the hash-mechanism?
Thanks a lot.

Try jsonString.merge(my_hash) ?
My understanding is that the variable called jsonString is actually a hash, not a json string. If you wanted to convert that hash to a real JSON string, you could import the json module (using require 'json') than call jsonStrong.to_json, but once you've converted the hash to a string it's more difficult to had other hashes to it. It's best to add all the hashes together, then convert the result to json.

Related

trying to push two specific values into another array as a key value pair using typescript

Newbie here and this is a project I'm building to learn. I'm going around in circles so forgive my ignorance please. I'm now not even sure that what I want to do is possible. I also understand that there are probably better ways to achieve my ultimate goal but this is what I have.
I have an array that includes some user input.
"participants": [ {
"name": "Cristina",
"email": "cristina#gmail",
"yourPerson": "Richard",
"spouseEmail": "Richard#gmail" } ] }
I want to pull the "name" and "youPerson" values and use them as a key:value pair. So name would be the key and yourPerson would be the value.
I thought I could use a forEach but no matter what I do I either get an undefined array or I copy the entire array, not just those two fields.
here is my code at the moment:
participantArray = [];
namePlusSpouseArray = [];
submitParticipant() {
this.participantArray.push(this.participantForm.value);
console.log(this.participantArray)
this.createNamePlusSpouseArray();
}
createNamePlusSpouseArray() {
this.participantArray.forEach(name => {
this.namePlusSpouseArray.push(this.participantArray[name]);
console.log(this.namePlusSpouseArray)
});
}
Not sure if you want a result array of key value pairs, or you want 1 object/map/dictionary/lookup of name -> youPerson
Assuming you want an array containing key value pairs, you can use map
this.namePlusSpouseArray = this.participantArray.map(participant => ({
[participant.name]: participant.youPerson
});
If you want a lookup of name -> youPerson, the "namePlusSpouseArray" shouldn´t be an array but instead just an object
namePlusSpouseLookup = {};
this.participantArray.forEach(participant => {
this.namePlusSpouseLookup[participant.name] = participant.youPerson;
});
The simplest solution is:
const participantArray = {
"participants": [ { "name": "Cristina", "email": "cristina#gmail", "yourPerson": "Richard", "spouseEmail": "Richard#gmail" } ] };
const createPair = participants => {
return participants.map(participant =>
({ [participant.name]: participant.yourPerson}))
}
console.log(createPair(participantArray.participants));

How to convert JSON object into an array in React Native

I am getting a JSON object from Firebase. I am trying to convert it into an array of objects.
I can solve this by getting childs from Firebase one-by-one and add them into array however, that is not a good practice for my case.
The format of JSON object is as following:
key: {
id1: {some stuff here},
id2: {some other stuff},
...
}
Now what I want to get from this JSON object is :
arrayName: [
{id1:{some stuff here},
id2:{some other stuff}
]
Hope my description if fully understandable.
Any help would be appreciated
This is just plain javascript, it has nothing to do with react native. By the way, you can use Object.keys to get an array with all the keys, then map the strings as objects:
const x = {foo: 11, bar: 42};
const result = Object.keys(x).map(key => ({[key]: x[key]}));
console.log(result);
This code worked for me.
const JSONString = res.data;
object = JSON.parse(JSONString);
array = Object.keys(object).map(function(k) {
return object[k];
});
Where res.data is the response I am getting from an api
Using Object.entries, you can avoid the extra hash lookup on every item.
const x = { foo: 11, bar: 42 };
const result = Object.entries(x).map(([key, val]) => ({
[key]: val
}));
console.log(result);

how to merge values in a list of map in ruby

say I have data structure like List< MAP< String, List>>, I only want to keep the List in map's value,
Like, I want to convert following example:
x = [{"key1" => ["list1", "list1"]}, {"key2" => ["list2", "list2"]},
{"key3" => ["list3", "list3"]}]
to:
y = [["list1", "list1"], ["list2", "list2"], ["list3", "list3"]]
Is there any quick way to do this? Thanks
The quickest thing that comes to mind is to leverage flat_map.
x = [ { "key1" => ["list1", "list1"] },
{ "key2" => ["list2", "list2"] },
{ "key3" => ["list3", "list3"] }]
y = x.flat_map(&:values)
=> [["list1", "list1"], ["list2", "list2"], ["list3", "list3"]]
flat_map is an instance method on Enumerable (https://ruby-doc.org/core-2.6.3/Enumerable.html#method-i-flat_map)
values is an instance method on Hash (https://ruby-doc.org/core-2.6.3/Hash.html#method-i-values)
If you only have 1 key in those hashes then you can do it like this:
y = x.map { |h| h.values[0] }

Generate from two ruby arrays an appropriate JSON output

I have two simple ruby arrays and a JSON string mapping the elements of the first array to the elements of the second array:
keys = [:key0, :key1, :key2]
values = [:value0, :value1, :value2]
jsonString = {keys[0] => values[0], keys[1] => values[1], keys[2] => values[2]}
Writing this to a file:
file.write(JSON.pretty_generate(jsonString))
results into a nicely printed json object:
{
"key0": "value0",
"key1": "value1",
"key2": "value2"
}
But how can I generate the same output of two much bigger arrays without listing all these elements explicitly?
I just need something like
jsonString = {keys => values}
but this produces a different output:
{
"[:key0, :key1, :key2]":
[
"value0",
"value1",
"value2"
]
}
How can I map the two without looping over both?
array = keys.zip(values)
#=> [[:key0, :value0], [:key1, :value1], [:key2, :value2]]
Array#zip merges elements of self to the corresponding elements of the argument array and you get an array of arrays. This you can convert into a hash ...
hash = array.to_h
# => {:key0=>:value0, :key1=>:value1, :key2=>:value2}
... and the hash you can turn into a json string.
jsonString = JSON.pretty_generate(hash)
puts jsonString
#{
# "key0": "value0",
# "key1": "value1",
# "key2": "value2"
#}
Use Array#zip to make pairs of values and then make hash of them:
keys = [:key0, :key1, :key2]
values = [:value0, :value1, :value2]
Hash[keys.zip values]
# => {:key0=>:value0, :key1=>:value1, :key2=>:value2}

Swift HTTP POST 2D array

The question is: in which format to send this array to remote URL? JSON or as array?
Is it possible to send it as simple array?
What I want to do is, to send 2d array to url. The array looks like following:
[
"deviceID" => "123456789"
"answers" => array(
1=>"a",
2=>"b"
...
)
]
Now a bit of code:
I have the following Dictionary:
var postJSON = [ids[0]:answersArray[0], ids[1]:answersArray[1], ids[2]:answersArray[2]] as Dictionary => [2: B, 1: B, 3: B]
Now, I want to create another Dictionary, like: ["deviceID", "123456789"], later concatenate these two Dictionaries onto one and JSON encode the result array.
How can I realize it?
For the POST I use:
var URL: NSURL = NSURL(string: "http://example.com/en/check-answers")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
var bodyData = // a JSON encode here
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
You can just build a new dictionary using your answers object and the deviceID key/value pair:
let answers = ["a", "b", "c"] // build this any way you want
let device = "123456789"
let payload = ["answers" : answers, "deviceID" : device]
let body = try! NSJSONSerialization.dataWithJSONObject(payload, options: [])
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = body
// now issue request
That creates JSON that looks like:
{"answers":["a","b","c"],"deviceID":"123456789"}
If you want to see it as the server gets it, you could have PHP code that takes that and prints it:
<?
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);
$body = json_decode($raw_post_data, true);
header("Content-Type: text/plain");
print_r($body);
?>
It looks like:
Array
(
[answers] => Array
(
[0] => a
[1] => b
[2] => c
)
[deviceID] => 123456789
)
Obviously, I wouldn't generally do print_r or var_dump, but rather would build a JSON response (set application/json for the Content-Type header, use json_encode to build response, etc.), but I wanted to show the associative array in more of a native PHP syntax. But hopefully this illustrates the idea, nonetheless.
By the way, if you wanted to really represent answers, itself, as a dictionary, you can do that, too, e.g.:
let answers = ["1" : "a", "2" : "b", "3" : "c"]
Just notice that the keys, 1, 2, and 3 must be strings, not numbers (it's a constraint of JSON, not of dictionaries in Swift).
Anyway, the resulting JSON would look like
{"answers":{"2":"b","1":"a","3":"c"},"deviceID":"123456789"}
And in PHP, that would look like:
Array
(
[answers] => Array
(
[2] => b
[1] => a
[3] => c
)
[device] => 123456789
)

Resources