Json creation in ruby for a list - arrays

I am new to Ruby.
I want to create a JSON file for a group of elements.
For this, I am using eachfunction to retrieve the datas. I want to create json as follows for the 4 length array,
'{
"desc":{
"1":"1st Value",
"2":"2nd value"
"3":"3rd Value",
"4":"4th value"
},
}'
This is my array iteration,
REXML::XPath.each( doc, "//time" ) { |element1|
puts element1.get_text
}
I know here is the simple code to generate a JSON,
require 'json/add/core'
class Item < Struct.new(:id, :name); end
chair = Item.new(1, 'chair')
puts JSON.pretty_generate(chair)
This syntax will generate a json as follows,
{
"json_class": "Item",
"v": [
1,
"chair"
]
}
But I'm not sure how to do that to make JSON for my elements as stated above. Google search didn't give me a proper way to do this.
Can anyone help me here?

it means this?:
require 'json'
my_arr= ["1st Value","2nd Value","3rd Value","4th Value"]
tmp_str= {}
tmp_str["desc"] = {}
my_arr.each do |x|
tmp_str["desc"]["#{x[0]}"] = x
end
puts JSON.generate(tmp_str)
you can iterate the string array ,then take the strings to hash object.JSON can easy to parse Hash objcect .

Related

Convert Array of objects to Array with only values

I have an array (obj_values) of objects
[
#<User id: 1, name: "Kostas">,
#<User id: 2, name: "Moufa">,
...
]
And I want to convert this into an Array with only the values from above objects, so it will look like:
[
1, Kostas
2, Moufa
]
I can do it like this:
obj_table = []
obj_values.each do |ext|
ext.each do |obj|
obj_table.push([obj.id, obj.name].join(","))
end
end
However with this approach I need to explicitly specify what attributes I want to push (obj.id and obj.name), is there a way to push whole data from object without the need to specify each attribute separately?
Use .attributes to get a hash of all the attributes on the model. Call .values on it to get just the values without the keys.
Using your code:
obj_table = []
obj_values.each do |ext|
ext.each do |obj|
obj_table.push(obj.attributes.values.join(","))
end
end
Though there are better ways. I suggest you look into .map and .flat_map.
obj_table = obj_values.flat_map do |ext|
ext.map do |obj|
obj.attributes.values.join(",")
end
end
Yes, you can push data without specifying it separately. to push data you have to use an object.attributes.values
an object will be your active record object.
attributes will return a hash with all attributes of that object.
so you can change your loops into a single statement like:
obj_values.flat_map {|object_value| object_value.attributes.values }

Getting values from json array using an array of object and keys in Python

I'm a Python newbie and I'm trying to write a script to extract json keys by passing the keys dinamically, reading them from a csv.
First of all this is my first post and I'm sorry if my questions are banals and if the code is incomplete but it's just a pseudo code to understand the problem (I hope not to complicate it...)
The following partial code retrieves the values from three key (group, user and id or username) but I'd like to load the objects and key from a csv to make them dinamicals.
Input json
{
"fullname": "The Full Name",
"group": {
"user": {
"id": 1,
"username": "John Doe"
},
"location": {
"x": "1234567",
"y": "9876543"
}
},
"color": {
"code": "ffffff",
"type" : "plastic"
}
}
Python code...
...
url = urlopen(jsonFile)
data = json.loads(url.read())
id = (data["group"]["user"]["id"])
username = (data["group"]["user"]["username"])
...
File.csv loaded into an array. Each line contains one or more keys.
fullname;
group,user,id;
group,user,username;
group,location,x;
group,location,y;
color,code;
The questions are: can I use a variable containing the object or key to be extract?
And how can I specify how many keys there are in the keys array to put them into the data([ ][ ]...) using only one line?
Something like this pseudo code:
...
url = urlopen(jsonFile)
data = json.loads(url.read())
...
keys = line.split(',')
...
# using keys[] to identify the objects and keys
value = (data[keys[0]][keys[1]][keys[2]])
...
But the line value = (data[keys[0]][keys[1]][keys[2]]) should have the exact number of the keys per line read from the csv.
Or I must to make some "if" lines like these?:
...
if len(keys) == 3:
value = (data[keys[0]][keys[1]][keys[2]])
if len(keys) == 2:
value = (data[keys[0]][keys[1]])
...
Many thanks!
I'm not sure I completely understand your question, but I would suggest you to try and play with pandas. It might be as easy as this:
import pandas as pd
df = pd.read_json(<yourJsonFile>, orient='columns')
name = df.fullname[0]
group_user = df.group.user
group_location = df.group.location
color_type = df.color.type
color_code = df.color.code
(Where group_user and group_location will be python dictionaries).

Parse Array of JSON Objects in Crystal lang

Suppose I've got a simple JSON mapped object in Crystal lang, e.g.:
class Item
JSON.mapping(
id: UInt32,
name: String,
)
end
I can parse individual objects from JSON strings easily like so:
foo = Item.from_json(%({"id":1,"name":"Foo"}))
puts "OK: foo=#{foo}"
# => OK: foo=Item(#id=1, #name="Foo")
But how would I parse an array of Items from a JSON string? I've tried a few approaches but am not sure how to proceed, e.g.:
items_str = %([{"id":1,"name":"Foo"},{"id":2,"name":"Bar"}])
items : Array(Item) = JSON.parse(items_str)
# => Error in foo.cr:15: type must be Array(Item), not JSON::Any
Of course, I'd also like to be able to do this with a JSON pull parser, so presumably there's some mapping trick or type hint I'm missing. Ideas?
Found it in this spec. So, you can use Array(Item).from_json:
items = Array(Item).from_json %([{"id":1,"name":"Foo"},{"id":2,"name":"Bar"}])
items.first.id #=> 1
items.first.name #=> "Foo"
items.last.id #=> 2
items.last.name #=> "Bar"

Read MongoDB array into perl and walk data

I am trying to capture an array from my MongoDB database into my Perl script and read each element. This is something that I thought would be simple, but for some dumb reason it is kicking my rearend.
My MongoDB Document (in part)
"members" : [
"5713b2d46d210e51836de591",
"me",
"you",
"him",
"her"
],
Perl code
$document = $database -> get_collection('my_collection')->find_one({_id => $oid});
#members = $document->{'members'};
print Dumper #members;
foreach $member (#members)
{
print "member = $member\n";
}
exit;
Output I am getting:
$VAR1 = [
'5713b2d46d210e51836de591',
'me',
'you',
'him',
'her'
];
member = ARRAY(0x47fa398)
Looking at the last line I see that I am being passed a reference to the array instead of the values. So I tried accessing via $member[0] or $member[1] but that just returns the same ARRAY(0x*****).
PLEASE HELP, I am sure it is something stupid.
Thanks!
Steven
I'm not familiar with Mongo, but looking at the output, your #members array has one element - an array ref (as you suspected). Since Mongo is returning an arrayref, you're best to store that in a scalar and access it like so;
my $members = $document->{'members'};
print "second item returned is: ", $members->[1];
print "The complete contents:\n";
for my $item ( #$members ) {
print " ", $item;
}

Iterate JSON array and find all matched values

So I am trying to find all elements within the json array below with an email with the domain example.com
JSON Array used:
[{"addedAt"=>123456,
"vid"=>123456,
"canonical-vid"=>123456,
"merged-vids"=>[],
"portal-id"=>123456,
"is-contact"=>true,
"profile-token"=>"portal-token-goes-here",
"profile-url"=>"portal-url-goes-here",
"properties"=>{"firstname"=>{"value"=>"Ramon"}, "lastmodifieddate"=>{"value"=>"12345"}, "company"=>{"value"=>"Some Company"}, "lastname"=>{"value"=>"Carleones"}},
"form-submissions"=>
[{"conversion-id"=>"some-convo-id-goes-here",
"timestamp"=>123456,
"form-id"=>"form-id-goes-here",
"portal-id"=>405406,
"page-url"=>"page-url-goes-here",
"content-type"=>"standard-page",
"page-title"=>"page-title-goes-here",
"title"=>"title-goes-here",
"first-visit-url"=>"first-visit-url-goes-here",
"first-visit-timestamp"=>123456,
"meta-data"=>[]}],
"identity-profiles"=>
[{"vid"=>123456,
"saved-at-timestamp"=>123456,
"deleted-changed-timestamp"=>0,
"identities"=>[{"type"=>"EMAIL", "value"=>"ramon#example.com", "timestamp"=>123456}, {"type"=>"Important", "value"=>"some-value", "timestamp"=>123456}]}],
"merge-audits"=>[]},
{"addedAt"=>123456,
"vid"=>123456,
"canonical-vid"=>123456,
"merged-vids"=>[],
"portal-id"=>123456,
"is-contact"=>true,
"profile-token"=>"portal-token-goes-here",
"profile-url"=>"profile-url-goes-here",
"properties"=>{"firstname"=>{"value"=>"Sally"}, "lastmodifieddate"=>{"value"=>"123456"}, "company"=>{"value"=>"Acme Inc."}, "lastname"=>{"value"=>"Jackson"}},
"form-submissions"=>
[{"conversion-id"=>"some-convo-id-goes-here",
"timestamp"=>123456,
"form-id"=>"some-form-id",
"portal-id"=>123456,
"title"=>"Big Freakin Title",
"meta-data"=>[]}],
"identity-profiles"=>
[{"vid"=>123456,
"saved-at-timestamp"=>123456,
"deleted-changed-timestamp"=>0,
"identities"=>[{"type"=>"EMAIL", "value"=>"sjackson#acme-example.com", "timestamp"=>123456}, {"type"=>"Team Lead", "value"=>"some-value", "timestamp"=>123456}]}],
"merge-audits"=>[]
}]
Here is the code I was trying:
I used factory girl and used an instance variable:
##json_array.contacts_obtained is a hash - contacts_obtained is the key, and the
#value is the actual json array above.
#json_array.contacts_obtained.detect do |i| i['identity-profiles'][0]['identities'][0]['value'] == /#example.com/
puts i
end
I wasn't sure if it was ok to do a regex there like that. It doesn't appear to work when I tried that. So I was wondering if there was another way to do this.
I am trying to obtain all the elements with #example.com domain so I can 'pop' them or remove them from the json array. Essentially I need a filter. That will filter out all the array elements with certain domain emails.
You are almost there. Use =~ instead of == iy ou want to match a string with a regexp:
#json_array.contacts_obtained.select do |i|
i['identity-profiles'][0]['identities'][0]['value'] =~ /#example.com/
end

Resources