How to grab data from JSON in CoffeeScript? [duplicate] - json

This question already exists:
Closed 10 years ago.
Possible Duplicate:
How to extract specific data from JSON using CoffeeScript?
I want to grab a specific piece of data from a massive JSON string. The entire string would be more than 10 pages long if posted here, so I'm just including an example snippet:
{ name: '',
keys:
[ 'statType',
'count',
'dataVersion',
'value',
'championId',
'futureData' ],
object:
{ statType: 'TOTAL_SESSIONS_PLAYED',
count: { value: 5 },
dataVersion: 0,
value: { value: 5 },
championId: { value: 31 },
futureData: null },
encoding: 0 }
How can I use CoffeeScript to:
parse that string to locate the object with a specific value, such as TOTAL_SESSIONS_PLAYED,
take the numerical value from that object (the value field), and
ideally, append that value into an external text file?
I am pretty much a super noob programmer. Basically, how could I, in this example, take that 5 value from the object labelled TOTAL_SESSIONS_PLAYED, and append it into a text file using CoffeeScript?

Whether you're doing this in the browser or in Node, you should be able to pass the JSON string to JSON.parse and pick out the value you want. You can then append to a file using Node's fs module like this: https://stackoverflow.com/a/11267583/659910.
fs = require 'fs'
# Sample JSON string.
json = '{ "statType": "TOTAL_SESSIONS_PLAYED", "count": { "value": 5 }, "dataVersion": 0 }'
data = JSON.parse(json)
fs.appendFile('/tmp/data.txt', data.count.value, (error) -> throw error if error)

Related

Parse multi level JSON with Ruby

I am trying to parse the JSON file below. The problem is I cannot return "Mountpoint" as a key. It only gets parsed as a value. This is the command I am using to parse it json_data = JSON.parse(readjson). The reason I guess that it's a key is because if I run json_data.keys only EncryptionStatus and SwitchName are returned. Any help would be greatly appreciated.
{
"EncryptionStatus": [
{
"MountPoint": "C:",
"VolumeStatus": "FullyEncrypted"
},
{
"MountPoint": "F:",
"VolumeStatus": "FullyEncrypted"
},
{
"MountPoint": "G:",
"VolumeStatus": "FullyEncrypted"
},
{
"MountPoint": "H:",
"VolumeStatus": "FullyEncrypted"
}
],
"SwitchName": [
"LAN",
"WAN"
]
}
I tried using dig as a part of my JSON.parse but that didn't seem to help me.
JSON data can have multiple levels.
Your JSON document is a
Hash (Dictionary/Map/Object in other languages) that has two keys ("EncryptionStatus", "SwitchName"),
The value for the "EncryptionStatsu" key is an Array of Hashes (with keys "MountPoint" and "VolumeStatus").
# assuming your JSON is in a file called "input.json"
data = File.read("input.json")
json = JSON.parse(data)
json["EncryptionStatus"].each do |encryption_status|
puts "#{encryption_status["MountPoint"]} is #{encryption_status["VolumeStatus"]}"
end
This will print out
C: is FullyEncrypted
F: is FullyEncrypted
G: is FullyEncrypted
H: is FullyEncrypted
If you want to access a specific item you can look at the dig method. E.g.
json.dig("EncryptionStatus", 3)
Would return the information for mountpoint "H"

How to define every element of request body as string in swagger OPENAPI? [duplicate]

This question already has answers here:
Swagger HashMap property type
(2 answers)
Swagger editor dictionary parameter definition
(1 answer)
Swagger complex response model with dynamic key value hash maps
(3 answers)
Closed 11 months ago.
The request body is JSON format and like this:
{
"subject": "email title",
"body": "email message",
"metadata" {
"key1" : "123"
"key2" : "345"
}
}
The problem is the value of metadata is a map (object), and the elements are not defined. Users can give any key-value pair in the metadata as they need, as long as its string. I'm writing a swagger openapi file to define that -- any key-value pair in the metadata should be string -- but I don't know how to. Here's what I have:
subject:
type: string
body:
type: string
metadata:
type: object
items:
type: string
The thought is I want to check if every element under metadata is string, but this is not working. I'm pretty new on swagger, and I'd appreciate any help!

How to get value from specific key in NodeJS JSON [duplicate]

This question already has an answer here:
Getting value from object in javascript
(1 answer)
Closed 6 years ago.
{
"id": 83,
"key": "hello",
"en": "Hello",
"mm": "This is greeting",
"created_at": "2016-12-05T10:14:02.928Z",
"updated_at": "2017-01-31T02:57:11.181Z"
}
I'm trying to get value from mm key in NodeJS. I've tried to get translation["mm"] but it does not work at all. Please help me how to get mm from above data.
My current node version is 5.11
Edited The Answer. Now Its working for above object in question
You can use following function to access the keys of JSON. I have returned 'mm' key specifically.
function jsonParser(stringValue) {
var string = JSON.stringify(stringValue);
var objectValue = JSON.parse(string);
return objectValue['mm'];
}
JSON is an interchange format, meaning it's only a text representing data in a format that many applications can read and translate into it's own language.
Therefore, using node.js you should parse it first (translate it to a javascript object) and store the result in a variable:
var obj = JSON.parse(yourJSONString);
Then, you can ask for any of it properties:
var mm = obj.mm;

Using JPATH, how do I select a JSON value inside another JSON string?

I have the following JSON (simplified / minimized to show only pertinent parts) returned from a web service:
{
"results": [{
"paramName": "OutputPolyline",
"dataType": "String",
"value": "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"
}],
"messages": []
}
I use the following code to parse the JSON and grab the value of the "value" key:
JObject obj = JObject.Parse(json);
JToken token = obj.SelectToken("$.results[?(#.paramName == 'OutputPolyline')]['value']");
Console.WriteLine(token.Path + " -> " + token);
The above code returns the entire value string as expected, like such "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"
Building on the above code, how do I get only the value of the paths key? In this example, return only [[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]
You cannot extract the path values from the root object via a single JsonPath query since the value of the value property is just a string literal that happens itself to be re-serialized JSON. It needs to be extracted and recursively parsed as JSON after first trimming off the # character, and Json.NET has no built-in query operator to do that as of the current version, 9.0.1.
Thus you need to do something like:
JToken token = obj.SelectToken("$.results[?(#.paramName == 'OutputPolyline')]['value']");
var paths = JToken.Parse(token.ToString().Trim('#')).SelectToken("paths");
Sample fiddle.

Dynamically build json using groovy

I am trying to dynamically build some json based on data I retrieve from a database. Up until the opening '[' is the "root" I guess you could say. The next parts with name and value are dynamic and will be based on the number of results I get from the db. I query the db and then the idea was to iterate through the result adding to the json. Can I use jsonBuilder for the root section and then loop with jsonSlurper to add each additional section? Most of the examples I have seen deal with a root and then a one time "slurp" and then joining the two so wasn't sure if I should try a different method for looping and appending multiple sections.
Any tips would be greatly appreciated. Thanks.
{
"hostname": "$hostname",
"path": "$path",
"extPath": "$extPath",
"appName": "$appName",
"update": {"parameter": [
{
"name": "$name",
"value": "$value"
},
{
"name": "$name",
"value": "$value"
}
]}
}
EDIT: So what I ended up doing was just using StringBuilder to create the initial block and then append the subsequent sections. Maybe not the most graceful way to do it, but it works!
//Create the json string
StringBuilder json = new StringBuilder("""{
"hostname": "$hostname",
"path": "$path",
"extPath": "$extPath",
"appName": "$appName",
"update": {"parameter": ["""
)
//Append
sql.eachRow("""<query>""",
{ params ->
json.append("""{ "name": "params.name", "value": "params.value" },""");
}
)
//Add closing json tags
json.append("""]}}""")
If I got your explanation correctly and if the data is not very big (it can live in memory), I'd build a Map object (which is very easy to work with in groovy) and convert it to JSON afterwards. Something like this:
def data = [
hostname: hostname,
path: path,
extPath: extPath,
appName: appName,
update: [parameter: []]
]
sql.eachRow(sqlStr) { row ->
data.update.parameter << [name: row.name, value: row.value]
}
println JsonOutput.toJson(data)
If you're using Grails and Groovy you can utilize grails.converters.JSON.
First, define a JSON named config:
JSON.createNamedConfig('person') {
it.registerObjectMarshaller(Person) {
Person person ->
def output = [:]
output['name'] = person.name
output['address'] = person.address
output['age'] = person.age
output
}
}
This will result in a statically defined named configuration for the Object type of person. Now, you can simply call:
JSON.use('person') {
Person.findAll() as JSON
}
This will return every person in the database with their name, address and age all in one JSON request. I don't know if you're using grails as well in this situation though, for pure Groovy go with another answer here.