convert JSON array to Ruby Hash (of hashes) - ruby

I'm trying to convert some API response data into a Ruby hash or array so I can more easily work with it. Here's the JSON string being returned by the API:
[
{
"id": 2,
"name": "TestThing",
"token": "B2CA27221DB976E48248F26756289B91"
},
{
"id": 3,
"name": "AnotherTestThing",
"token": "EF16E5F20B8463E48DBF3BA8F0E1102A"
}
]
I believe that is a JSON array? I tried doing JSON.parse on that string, but got (JSON::ParserError)r/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/json/common.rb:148:in 'parse': 746: unexpected token at '1511
What is the best way to convert this into something I can easily work with? My real goal here is to iterate over the tokens returned.

require 'json'
array = '[
{
"id": 2,
"name": "TestThing",
"token": "B2CA27221DB976E48248F26756289B91"
},
{
"id": 3,
"name": "AnotherTestThing",
"token": "EF16E5F20B8463E48DBF3BA8F0E1102A"
}
]'
JSON.parse(array)

My question did not show the full string I was trying to JSON.parse. I only put what I was trying to parse. I accidentally left some floating data before the JSON part of my string. Now that I have deleted that, it is working.

Related

additional "/" (slash) from response assertion is showing in Jmeter

I want to use response assertion to match the response from server, here when I am getting responses it shows like {
"per_page": 6,
"total": 12,
"data": [
{
"last_name": "Lawson",
"id": 7,
"avatar": "https://reqres.in/img/faces/7-image.jpg",
"first_name": "Michael",
"email": "michael.lawson#reqres.in"
},
But in response assertion it showing like
Assertion failure message:Test failed: text expected to contain /{
"per_page": 6,
"total": 12,
"data": [
{
"last_name": "Lawson",
"id": 7,
"avatar": "https://reqres.in/img/faces/7-image.jpg",
"first_name": "Michael",
"email": "michael.lawson#reqres.in"
},
{
and therefor it gets failing even though its matching but due to addition / (slash), its getting failed.
JMeter doesn't "add" slashes anywhere, it's just a matter of visualization, you're getting your pattern surrounded with slashes as there is a mismatch, basically JMeter fails to find what you put in the "Patterns to test" in the application response
Demo:
See lines 472 and 480 in the ResponseAssertion source
So make sure that your response contains the pattern and be aware that every line brake or empty space matters so if your server returns non-formatted string and you're expecting a "pretty" one - the assertion will fail.
We cannot suggest the best option without seeing you actual response, however full-text comparing 2 JSON entities doesn't seem a good approach to me in terms of robustness and reliability, you might want to consider JSON Assertion or JSON JMESPath Assertion instead

Ruby - Parse a file into hash

I've a file containing hundreds of object and value combination like below manner. I want to get input from user as object name & numeric value and return that associated value.
Object cefcFRUPowerOperStatus
Type PowerOperType
1:offEnvOther
2:on
3:offAdmin
4:offDenied
5:offEnvPower
6:offEnvTemp
Object cefcModuleOperStatus
Type ModuleOperType
1:unknown
2:ok
3:disabled
4:okButDiagFailed
5:boot
6:selfTest
E.g. - input -
objectName = 'cefcModuleOperStatus'
TypeNumber = '4'
Return - 'okButDiagFailed'
I am not aware of Ruby and get this done to help my peer. So please excuse if this is a novice question.
Note:- I've to create the file so with any file format it would be a great help.
If like you say you have control over creating the original data file, then creating it in json format would make accessing it trivial.
Here is a repl.it of complete working example. Just select the main.rb file and hit run!
For example if you create json file like:
data.json
{
"cefcFRUPowerOperStatus": {
"type": "PowerOperType",
"status": {
"1": "offEnvOther",
"2": "on",
"3": "offAdmin",
"4": "offDenied",
"5": "offEnvPower",
"6": "offEnvTemp"
}
},
"cefcModuleOperStatus": {
"type": "ModuleOperType",
"status": {
"1": "unknown",
"2": "ok",
"3": "disabled",
"4": "okButDiagFailed",
"5": "boot",
"6": "selfTest"
}
}
}
Then parsing it and accessing it in Ruby is as simple as :
require 'json'
file = File.read('data.json')
data = JSON.parse(file)
#accessing this data is simple now:
puts data["cefcModuleOperStatus"]["status"]["4"]
# > okButDiagFailed
Note: that this JSON format will work if your statuses are unique. If they are not, you can still use this way, but you will need to convert JSON to an array format. Let me know if this is the case and I can show you how to modify the json and ruby code for this.
Hope that helps, let me know if you have further questions about how this works.

How to read value from JSON object?

I'm trying to read individual value from be json array object to display in the page. I have tried with below code but couldn't make it. Please advise what am i doing wrong here.
Apperciate your help.
You can get the length of a JavaScript array via its property length. To access the array Reference in your object, you can use dot notation.
In combination, the following should do what you expect:
var obj = {
"Reference": [
{
"name": "xxxxxxxx",
"typeReference": {
"articulation": 0,
"locked": false,
"createdBy": {
"userName": "System",
},
"lastModifiedBy": {
"userName": "System",
},
"lastModified": 1391084398660,
"createdOn": 1391084398647,
"isSystem": true
},
...
},
...
]
};
console.log(obj.Reference.length);
In case you are actually dealing with a JSON string, not a JavaScript object, you will need to parse it first via JSON.parse().
You get the length of an array by simply access the length attribute.
For example [0,1,2,3].length === 4.
If you just want to loop through the array, use forEach or map instead of a for loop. It's safer, cleaner, less hassle and you don't meed to know the length.
E.g.
[0,1,2,3].forEach(num => console.log(num))

using ruby json library to parse json data into a hash some keys missing

lets say I have this json data file
{
"page": {
"title": "Example Page"
},
"employers": {
"name": "Jon"
},
"employees": [
{ "name": "Mike", "nicknames": ["Superman"] },
{ "name": "Peter", "nicknames": ["Peet", "Peetee", "Peterr"] }
]
}
this data.json file exist as a file outside of the script
I have these 3 lines to read and parse it with json ruby library
data = File.read("data.json")
obj = JSON.parse(data)
puts obj.values
in my terminal it comes out to be like this
{"title"=>"Example Page"}
{"name"=>"Jon"}
{"name"=>"Mike", "nicknames"=>["Superman"]}
{"name"=>"Peter", "nicknames"=>["Peet", "Peetee", "Peterr"]}
what happened to employers and employees? now I have the same key or name in this case. Its difficult for me to grab the values to use them.
Employers and employees are the keys for primary hash, and you requested values, that's why you get what you get. Try putting obj .

How to remove a key from a RethinkDB document?

I'm trying to remove a key from a RethinkDB document.
My approaches (which didn't work):
r.db('db').table('user').replace(function(row){delete row["key"]; return row})
Other approach:
r.db('db').table('user').update({key: null})
This one just sets row.key = null (which looks reasonable).
Examples tested on rethinkdb data explorer through web UI.
Here's the relevant example from the documentation on RethinkDB's website: http://rethinkdb.com/docs/cookbook/python/#removing-a-field-from-a-document
To remove a field from all documents in a table, you need to use replace to update the document to not include the desired field (using without):
r.db('db').table('user').replace(r.row.without('key'))
To remove the field from one specific document in the table:
r.db('db').table('user').get('id').replace(r.row.without('key'))
You can change the selection of documents to update by using any of the selectors in the API (http://rethinkdb.com/api/), e.g. db, table, get, get_all, between, filter.
You can use replace with without:
r.db('db').table('user').replace(r.row.without('key'))
You do not need to use replace to update the entire document.
Here is the relevant documentation: ReQL command: literal
Assume your user document looks like this:
{
"id": 1,
"name": "Alice",
"data": {
"age": 19,
"city": "Dallas",
"job": "Engineer"
}
}
And you want to remove age from the data property. Normally, update will just merge your new data with the old data. r.literal can be used to treat the data object as a single unit.
r.table('users').get(1).update({ data: r.literal({ age: 19, job: 'Engineer' }) }).run(conn, callback)
// Result passed to callback
{
"id": 1,
"name": "Alice",
"data": {
"age": 19,
"job": "Engineer"
}
}
or
r.table('users').get(1).update({ data: { city: r.literal() } }).run(conn, callback)
// Result passed to callback
{
"id": 1,
"name": "Alice",
"data": {
"age": 19,
"job": "Engineer"
}
}

Resources