Error parsing string to JSON - ruby

I have a below String in Ruby. is there any way by which i can convert this string into JSON
{
drawer: {
stations: {
tv: {
header: "TV Channels",
logos: {
one: "www1",
two: "www2",
three: "www3"
}
}
}
}
}
Ideally there should be double quotes before and after the terms( like "drawer" instead of drawer). But the data returned from server is in the above format.
I am trying to use the JSON library to parse the string.

require 'json'
'something'.to_json #=> "\"something\""

Related

Reference regex string In JSON response

How to reference regex string In the JSON response
url value(consumer(regex('/connectors/(.*?)/status')))
So that if I request '/connectors/foo/status' I get { "name": "foo" }
Please read the docs - https://docs.spring.io/spring-cloud-contract/docs/current/reference/html/project-features.html#contract-dsl-referencing-request-from-response
You'd need to do
response {
body(name: fromRequest().path(1))
}

How to Extract Json value from an array based on some value in sub array

I want to get the "id":1922 from the main array based on the "id":1 from the sub array 'media_type':
{
"data":[
{
"id":1922,
"media_count":1,
"title":"test",
"description":"Test",
"address":null,
"latitude":null,
"longitude":null,
"privacy":1,
"license":1,
"is_comment_disable":0,
"is_adult":0,
"media_type":{
"id":1,
"slug":"photo",
"title":"Photo"
}
}
]
}
Instead of converting json to object, you can use json parser
For reference: https://www.programcreek.com/java-api-examples/index.php?api=javax.json.stream.JsonParser
Try with JSON path to get value base on media_type
$..data[?(#.media_type>0)].id

Single value vs Array in GraphQL Enum input types

How do you define an input type that either accepts a single enum value or an array of values in GraphQL?
According to GitHub GraphQL API,
{
securityVulnerabilities(first: 3, ecosystem: RUBYGEMS) {
nodes {
advisory {
description
}
}
}
}
But I think array can be good because user can search across ecosystem.
{
securityVulnerabilities(first: 3, ecosystem: [RUBYGEMS, NPM]) {
nodes {
advisory {
description
}
}
}
}
You can do this by defining the input value as an array [] of your defined Enum, something like:
enum MyEnum {
RUBYGEMS
NPM
}
type Query {
securityVulnerabilities(ecosystem: [MyEnum!]): MyReturnObject
}
And then you can query it like:
{
securityVulnerabilities(ecosystem: [RUBYGEMS, NPM]) {
....
}
}
And it works with both an array or a single value:
{
securityVulnerabilities(ecosystem: RUBYGEMS) {
....
}
}
The GraphQL spec explains the following:
If the value passed as an input to a list type is not a list and not
the null value, then the result of input coercion is a list of size
one [...]

How to pass GraphQLEnumType in mutation as a string value

I have following GraphQLEnumType
const PackagingUnitType = new GraphQLEnumType({
name: 'PackagingUnit',
description: '',
values: {
Carton: { value: 'Carton' },
Stack: { value: 'Stack' },
},
});
On a mutation query if i pass PackagingUnit value as Carton (without quotes) it works. But If i pass as string 'Carton' it throws following error
In field "packagingUnit": Expected type "PackagingUnit", found "Carton"
Is there a way to pass the enum as a string from client side?
EDIT:
I have a form in my front end, where i collect the PackagingUnit type from user along with other fields. PackagingUnit type is represented as a string in front end (not the graphQL Enum type), Since i am not using Apollo Client or Relay, i had to construct the graphQL query string by myself.
Right now i am collecting the form data as JSON and then do JSON.stringify() and then remove the double Quotes on properties to get the final graphQL compatible query.
eg. my form has two fields packagingUnitType (An GraphQLEnumType) and noOfUnits (An GraphQLFloat)
my json structure is
{
packagingUnitType: "Carton",
noOfUnits: 10
}
convert this to string using JSON.stringify()
'{"packagingUnitType":"Carton","noOfUnits":10}'
And then remove the doubleQuotes on properties
{packagingUnitType:"Carton",noOfUnits:10}
Now this can be passed to the graphQL server like
newStackMutation(input: {packagingUnitType:"Carton", noOfUnits:10}) {
...
}
This works only if the enum value does not have any quotes. like below
newStackMutation(input: {packagingUnitType:Carton, noOfUnits:10}) {
...
}
Thanks
GraphQL queries can accept variables. This will be easier for you, as you will not have to do some tricky string-concatenation.
I suppose you use GraphQLHttp - or similar. To send your variables along the query, send a JSON body with a query key and a variables key:
// JSON body
{
"query": "query MyQuery { ... }",
"variables": {
"variable1": ...,
}
}
The query syntax is:
query MyMutation($input: NewStackMutationInput) {
newStackMutation(input: $input) {
...
}
}
And then, you can pass your variable as:
{
"input": {
"packagingUnitType": "Carton",
"noOfUnits": 10
}
}
GraphQL will understand packagingUnitType is an Enum type and will do the conversion for you.

how can I iterate through this json document using ruby?

I have a ruby code block, as follows:
require "elasticsearch"
require "json"
search_term = "big data"
city = "Hong Kong"
client = Elasticsearch::Client.new log: true
r = client.search index: 'candidates', body:
{
query: {
bool: {
must: [
{
match: {
tags: search_term
}
},
{
match: {
city: city
}
}
]
}
}
}
It produces multiple returns like this one:
{"_index":"candidates","_type":"data",
"_id":"AU3DyAmvtewNSFHuYn88",
"_score":3.889237,
"_source":{"first":"Kota","last":"Okayama","city":"Tokyo","designation":"Systems Engineer","email":"user#hotmail.co.jp","phone":"phone","country":"Japan","industry":"Technology","tags":["remarks","virtualization big data"]}}
I want to iterate through it and extract various elements. I have tried
data = JSON.parse(r)
data.each do |row|
puts row["_source"]["first"]
end
and the error is:
no implicit conversion of Hash into String (TypeError)
What's the best way forward on this chaps?
I have the solution, I hope it helps somebody else. It took me hours of fiddling and experimentation. Here it is:
require "elasticsearch"
require "json"
search_term = "big data"
city = "Tokyo"
client = Elasticsearch::Client.new log: true
h = client.search index: 'swiss_candidates', body:
{
query: {
bool: {
must: [
{
match: {
tags: search_term
}
},
{
match: {
city: city
}
}
]
}
}
}
data = JSON.parse(h.to_json)
data["hits"]["hits"].each do |r|
puts r["_id"]
puts r["_source"]["first"]
puts r["_source"]["tags"][1]
puts r["_source"]["screened"][0]
end
The important thing seems to be to convert the elasticsearch result into something ruby friendly.
JSON.parse expects a String containing a JSON document, but you are passing it the Hash which was returned from client.search.
I'm not entirely sure what you are trying to achieve with that, why you want to parse something which is already a Ruby Hash into a Ruby Hash.

Resources