Ruby: Parsing Json statements that use x[{a:b, c:d}] - json

I'm parsing a JSON document like
{
"status": "ok",
"tick": {
"id": 101006380508,
"data": [
{
"id": "10100638050832281590023",
"amount": 0.2251,
}
]
}
}
I am currently doing:
data = JSON.parse(response.read_body)
data["tick"]["data"]["amount"]
and getting an error
Error: []': no implicit conversion of String into Integer (TypeError)
My objective is the get the amount

It's array that contains one hash, so you can get it as
data["tick"]["data"].first["amount"] # => 0.2251

Related

How to replace double quotes in a json string in Golang?

I have a problem parsing a string object to JSON with Golang.
there are double quotes in some fields values.
I'm trying to use a regex pattern but it doesn't work for me, I'm doing the conversion from bigquery which is based on the Golang code but it doesn't work for me.
{
"Responses": [],
"SessionParameters(Updated)": {
"counter-no-match-nombre": "($session.params.counter-no-match, 1)",
"message": "Hello."
},
"SystemFunctionResults": {
"SystemFunctionErrors": [
{
"Message": "Wrong type of argument for function "NONE", expected 1th argument to be one of type: ["number"]."
}
]
}
}
here a example
([:[,{]\s*)"(.?)"(?=\s[:,]}])
Test regex
SELECT
REGEXP_REPLACE('{
"obj1": "value is "test" of test, \"obj1\" val",
"result": "your result is "out" in our website",
"info": {
"x": [
{
"desc": "shjjfdsajfjkfsdkf, "sfsdfsdfdsf" fjkdfgjkfd."
}
]
}
}','([:\\[,{]\\s*)"(.*?)"(?:\\s*[:,\\]}])','NONE')
AS json_data;
I would appreciate your help, thanks

Output json stringify elements

I have a problem. I am using TypeScript and I get a response back. I want to output the information. How could I output e.g. internalCompanyCode and timestamp.
What I got
Element implicitly has an 'any' type because index expression is not of type 'number'.(
//const json = JSON.stringify(result, null, 2)
// json is the result of JSON.stringify(...)
const json = [
{
"internalCompanyCode": "007",
"moreInfo": [
{
"dimensions": {
"height": 27,
"width": 31,
"length": 61
},
"currenStatus": {
"arrived": {
"timestamp": "10:00:12"
}
}
}
]
}
]
console.log(json['internalCompanyCode'])
console.log(json['moreInfo']['dimensions']['height'])
To get data you don't have to stringify result. You have to use result before stringifying to json or have to parse json back to result if you did it
console.log(result[0]['internalCompanyCode']) //007
console.log(result[0]['moreInfo'][0]['currenStatus']['arrived']['timestamp']) // 10:00:12
console.log(result[0]['moreInfo'][0]['dimensions']['height']) //27
Your json object is actually a list so you will have to access it like json[0]['internalCompanyCode']

Umarshalling large unstructured REST/JSON Response

I'm having a heck of a time figuring out how to unmarshal a large unstructured json response into a usable object.
Here is a sample response (trimmed to show the part I'm having trouble with)
This has been greatly trimmed as this is a very large json response. I left the struct tags off below as well for simplicity.
{
"responseStatus": "ok",
"responseHeader": {
"status": "ok",
"requestId": "blah"
},
"responseData": {
"records": [
{
"name": "blah",
"site": {
"id": 1,
"name": "west"
},
"somevar1": "someval",
"somevar2": {
"x": 2,
"y": 1
},
"entries": [
{
"model": "100",
},
{
"model": "200",
}
]
},
]
}
So records is a large list of "objects". I need to convert these to a type I defined. The "entries" list also needs to be converted to its object type.
type Record struct {
Name string
Site map[string]string
Somevar1 string
Somevar2 map[string]string
Entries []Entry
}
type Entry struct {
Model string
}
Here I can get the responseData into an object I can iterate over:
results := data["responseData"].(map[string]interface{})
devices := results["records"].([]interface{})
for _, device := range devices {
fmt.Fprintf(os.Stdout, "%T\n", device)
fmt.Fprintf(os.Stdout, "%+v\n", device)
}
Here is a sample output from 1 iteration:
map[string]interface {}
map[name:foo site:map[id:2 name:somewhere somevar1: blah somevar2:map[x:1 y:2] entries:[map[model:100] map[model:200]
This is where I'm stuck. I need to take this line above and get convert it into my type Record while also converting the Entries to []Entry.
Change the Site and Somevar2 fields to map[string]interface{} or to a proper struct, because their corresponding json contains ints, so when you use only map[string]string it will fail.
Other than that your code works https://play.golang.com/p/rTgaXhXD1V6

Json object with nested objects, nested objects | mockable

I'm trying to create a test API in mockable.
What am I trying to create?
I'm trying to build an Json object with a Nested object which holds another nested object.
Example for use: store object => Store info => product list
What I expect to create
{
"Object": {
"id": 0,
"name": "Nova",
"nestedObject": {
{
"id": 1,
"name": "NestedNestedObject1",
},
{
"id": 2,
"name": "NestedNestedObject2",
},
}
Result I'm getting:
Error: Parse error on line 11:
...: { {
----------------------^
Expecting 'STRING', '}'
At NestedNestedObject2
How do I create a nested, nested object? If I'm correct mockable accepts pure Json
It depends on what you want to create and that depends on your API. The actual problem is that your JSON is not valid.
After your nestedObject there is just a { and that is wrong. In this case I assume you want to have an array of nestedObject (and perhaps also name should be nestedObjects) so fix would be (see the array []):
{
"Object": {
"id": 0,
"name": "Nova",
"nestedObject": [
{
"id": 1,
"name": "NestedNestedObject1"
},
{
"id": 2,
"name": "NestedNestedObject2"
}
]
}
}

Ruby: How to parse json to specific types

I have a JSON that I want to parse in Ruby. Ruby is completely new to me, but I have to work with it :-)
Here is my litte snippet, that should do the parsing:
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response)
this works pretty fine. The only downside is, I do not know the properties at the point where I use it, it is not typesafe. So I created the objects for it
class Announcements
##announcements = Hash # a map key => value where key is string and value is type of Announcement
end
class Announcement
##name = ""
##status = ""
##rewards = Array
end
And this is how the json looks like
{
"announcements": {
"id1" : {
"name": "The Diamond Announcement",
"status": "published",
"reward": [
{
"id": "hardCurrency",
"amount": 100
}
]
},
"id2": {
"name": "The Normal Announcement",
"players": [],
"status": "published",
"reward": []
}
}
}
So I tried JSON parsing like this
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response, Announcements)
But this is not how it works^^can anybody help me with this?