How to add key/value pair in hash with ruby laungage - ruby

I am using ruby 2.0.0, At present i have one demo.json file with following hash values:
{
"users":
{
"#jon" :
{
"name": "pradeep",
"Email": "pradeep#yahoo.com",
"area": "#jon",
"location": "#newyork"
},
"#smith" :
{
"name": "Smith",
"Email": "Joe#yahoo.com",
"area": "#smith",
"location": "#lverginia"
}
}
}
now i am taking json values in object using following codes:
require 'json'
json = File.read('demo.json')
obj = JSON.parse(json)
here #jon and #smith is usernames, Now i wants to take usernames via keyboard inputs and than all the other values inside of #jon with same keyboard.
Suppose i have one new user #david and his other values are like:
"name": "pradeep",
"Email": "pradeep#yahoo.com",
"area": "#jon",
"location": "#newyork"
i wants to add this in above demo.json file without remove other values, Any idea how can i do?
I tried to do this in this way:
obj["users"]
But as i got username via input so i cant hard code username after user key on "obj" object, Hope this make sense..

Read this JSON also .
I'd do as below :
require 'json'
json = JSON.parse(File.read("test.json"))
new_information_arry = ["users", "name", "Email", "area", "location"].map do |elem|
puts "please give the value of #{elem}"
[elem,gets.chomp]
end
new_information_hash = Hash[new_information_arry[1..-1]]
json['users'][new_information_arry.first.last] = new_information_hash
File.write("outputfile.json",JSON.pretty_generate(json))
I put the below content to my file 'test.json' :
{
"users":
{
"#jon" :
{
"name": "pradeep",
"Email": "pradeep#yahoo.com",
"area": "#jon",
"location": "#newyork"
},
"#smith" :
{
"name": "Smith",
"Email": "Joe#yahoo.com",
"area": "#smith",
"location": "#lverginia"
}
}
}
Then I ran the above code as below :
please give the value of users
#david
please give the value of name
pradeep
please give the value of Email
pradeep#yahoo.com
please give the value of area
#jon
please give the value of location
#newyor
And now my output file outputfile.json contains :
{
"users": {
"#jon": {
"name": "pradeep",
"Email": "pradeep#yahoo.com",
"area": "#jon",
"location": "#newyork"
},
"#smith": {
"name": "Smith",
"Email": "Joe#yahoo.com",
"area": "#smith",
"location": "#lverginia"
},
"#david": {
"name": "pradeep",
"Email": "pradeep#yahoo.com",
"area": "#jon",
"location": "#newyor"
}
}
}

Related

Turn a JSON array of key/value pairs into object properties

I'm trying to use JSONata to convert arrays of "key/value" objects into properties of the parent object. My input looks like this:
[
{
"city": "Ottawa",
"properties": [
{
"name": "population",
"value": 37
},
{
"name": "postalCode",
"value": 10001
},
{
"name": "founded",
"value": 1826
}
]
},
{
"city": "Toronto",
"properties": [
{
"name": "population",
"value": 54
},
{
"name": "postalCode",
"value": 10002
}
]
}
]
I'm struggling to generate the output I need, I've seen examples that reference explicit elements, like in this answer, but I need the properties to be converted "dynamically" since I don't know them in advance. I think I need something like this, but I'm missing some particular function:
$[].{
"city": city,
properties.name: properties.value
}
This is the output I need to generate:
[
{
"city": "Ottawa",
"population": 37,
"postalCode": 10001,
"founded": 1826
},
{
"city": "Toronto",
"population": 54,
"postalCode": 10002
}
]
The properties arrays don't always contain the same keys, but the city attributes are always present.
You can use the reduce operator, as described in the Grouping docs here:
$[].(
$city := city;
properties{ "city": $city, name: value }
)
You can play with it live: https://stedi.link/uUANwtE
Please try this expression.
$[].{
"city": $.city,
$.properties[0].name: $.properties[0].value,
$.properties[1].name: $.properties[1].value,
$.properties[2].name: $.properties[2].value,
$.properties[3].name: $.properties[3].value
}
https://try.jsonata.org/s1Ea4kUvo

Delete existing Records if they are not in sent array Rails 5 API

I need help on how to delete records that exist in the DB but not in array sent in a request;
My Array:
[
{ "id": "509",
"name": "Motions move great",
"body": "",
"subtopics": [
{
"title": "Tywan",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportations Gracious",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportation part",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
},
{
"name": "Motions kkk",
"body": "",
"subtopics": [
{
"title": "Transportations",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
}
]
Below is my implementation: where am going wrong?
#topics = #course.topics.map{|m| m.id()}
#delete= #topics
puts #delete
if Topic.where.not('id IN(?)', #topics).any?
#topics.each do |topic|
topic.destroy
end
end
it's not clear to me where, in your code, you pick the ids sent in the array you showed before... so I'm assuming like this:
objects_sent = [
{ "id": "509",
"name": "Motions move great",
"body": "",
"subtopics": [
{
"title": "Tywan",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportations Gracious",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportation part",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
},
{
"name": "Motions kkk",
"body": "",
"subtopics": [
{
"title": "Transportations",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
}
]
since you have your array like this, the only information you need to query on database is the ids (also, assuming the id's in the array are the id's on database, otherwise it wouldn't make sense). You can get them like this:
sent_ids = objects_sent.map{|o| o['id'].to_i}
Also, it seems to me that, for the code you showed, you want to destroy them based on a specific course. There would be 2 ways to do that. First, using the relationship (I prefer like this one):
#course.topics.where.not(id: sent_ids).destroy_all
Or you can do the query directly on the Topic model, but passing the course_id param:
Topic.where(course_id: #course.id).where.not(id: sent_ids).destroy_all
ActiveRecord is smart enough to mount that query correctly in both ways. Give it a test and see which works better for you

Filter an array in Ruby

In Ruby, I have a hash like below. How can I get the "name" of the "tag" where the tag_type is "LocationTag"? In this case, the returned value would be 'singapore'.
Is the best method just to do:
location = nil
tags.each do |t|
if t["tag_type"] == "LocationTag"
location = t.name
end
end
or does ruby have a better method for filtering hashes?
{
tags: [
{
"id": 81410,
"tag_type": "SkillTag",
"name": "angular.js",
"display_name": "Angular.JS",
"angellist_url": "https:\/\/angel.co\/angular-js"
},
{
"id": 84038,
"tag_type": "SkillTag",
"name": "bootstrap",
"display_name": "Bootstrap",
"angellist_url": "https:\/\/angel.co\/bootstrap"
},
{
"id": 1682,
"tag_type": "LocationTag",
"name": "singapore",
"display_name": "Singapore",
"angellist_url": "https:\/\/angel.co\/singapore"
},
{
"id": 14726,
"tag_type": "RoleTag",
"name": "developer",
"display_name": "Developer",
"angellist_url": "https:\/\/angel.co\/developer"
}
]
}
This will get you the first hit:
tags.detect{|tag| tag['tag_type'] == 'LocationTag'}['name']
This will give you all hits as an array
tags.select{|tag| tag['tag_type'] == 'LocationTag'}.map{|t| t['name']}
Check out the docs for Ruby#Enumerable for more details.
Ruby#Enumerable:detect
Ruby#Enumerable:select
(Thanks #PaulRichter for the comment... it's a nice clarifying addition to the post)
You can use find to stop the iteration once you've found a result:
location = tags.find { |t| t["name"] if t["tag_type"] == "LocationTag" }
Mind the errors that got fixed in the above: t.name and = "LocationTag".

json deserializing coming back empty

I took suggestions from here and tried to create a class with objects for the parts I need to parse from my json feed. I then tried to deserialize it before mapping the field contents to my objects but the deserialization returns nothing.
Here is the json feed content:
"data": [
{
"id": "17xxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxx",
"from": {
"name": "Lxxxxxx",
"category": "Sports league",
"id": "17xxxxxxxxxxxxx"
},
"picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQB4GscSy-2RHY_0&w=130&h=130&url=http\u00253A\u00252F\u00252Fwww.ligabbva.com\u00252Fquiz\u00252Farchivos\u00252Fbenzema-quiz-facebook.png",
"link": "http://www.xxxxxva.com/quiz/index.php?qid=34",
"source": "http://www.lxxxxva.com/modulos/redirectQuiz.php?name=benzema&q=34&time=1312827103",
"name": "DEMUESTRA CU\u00c1NTO SABES SOBRE... BENZEMA",
"caption": "www.xxxxxva.com",
"description": "Demuestra cu\u00e1nto sabes sobre Karim Benzema, delantero del Real Madrid.",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yj/r/v2OnaTyTQZE.gif",
"type": "video",
"created_time": "2011-08-08T18:11:54+0000",
"updated_time": "2011-08-08T18:11:54+0000",
"likes": {
"data": [
{
"name": "Jhona Arancibia",
"id": "100000851276736"
},
{
"name": "Luis To\u00f1o",
"id": "100000735350531"
},
{
"name": "Manuel Raul Guerrero Cumbicos",
"id": "100001485973224"
},
{
"name": "Emmanuel Gutierrez",
"id": "100000995038988"
}
],
"count": 127
},
"comments": {
"count": 33
}
},
{
"id": "17xxxxxxxxxxxxxxxx_xxxxxxxxxxxxx",
"from": {
"name"
and here is the code I am trying. I tried to also use the jsontextreader and loop through each tokentype and check each one and then read the value but this looks like it will turn out to be tedious.
....
//fetch the content
responsedata = reader.readtoend()
......
dim pp as facedata = JsonConvert.DeserializeObject(of faceData)(responsedata)
console.writeline(pp.id.tostring)
and the class objects
Public Class faceData
Public Property id() as string
Get
Return f_id
End Get
Set(ByVal value as string)
f_id =value
End Set
End Property
Private f_id as string
......
any response appreciated.
Does anyone have links to full code where it actually works using vb.net.

error given Sending json array in ajax request? using javascript

hihi i am doing a project regarding ajax (xmlHttRequest),
how am i going to call the title in the note session, because normally if you call start year is like, detail = eval....
then for loop it
inside should be
var start year=""
startyear += ...[i].startyear
something like this, but how am i going to call the title inside the note?
i try to call detail.notes.note.title it say is null or is not a object
this is json data:
{
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{
"id": "1",
"title": "Red House",
"url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html"
},
{
"id": "2",
"title": "Joo Chiat",
"url": "http://www.the-inncrowd.com/joochiat.htm"
},
{
"id": "3",
"title": "Bake",
"url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery"
}
]
}
]
}
}
Use http://jsonlint.com/ to help you out with JSON.
I got this...
Parse error on line 30:
... ] }
----------------------^
Expecting '}', ',', ']'

Resources