How to convert JSON to node.js object - json

I have a JSON tree like this that is being posted to my node.js (we'll call it message for the sake of this question):
var message = ["layer1": [
"color": "Blue",
"size": "small",
"layer2": [
"item1": "TEST"
]
]
]
How can I make it so I can access individual nodes and values in node.js, something like this:
var sample1 = message.layer1
var sample2 = message.layer1.layer2.item1
if I were to console.log(sample1) it would look like this:
["color": "Blue",
"size": "small",
"layer2": [
"item1": "TEST"
]
]
and console.log(sample2) would look like this:
"TEST"
Is this possible?

The syntax of your message variable is not Javascript (your message seems to be an array, but have key:value, which is not allowed in Javascript).
You have to replace "[" by "{" and "]" by "}" in your message to have a Javascript object. Then your sample1 and sample2 variables should work.

Related

Updating Nested JSON Array with new key and value from another key

I have have a JSON file where I have IDs with tasks. Some tasks can be empty. I want to put the ID into the tasks where tasks are not empty.
[
{
"id": 1961126,
"tasks": [
{
"id": 70340700,
"title": "Test1",
},
{
"id": 69801130,
"title": "Test15A",
}
]
},
{
"id": 1961126,
"tasks": []
}
]
I would like to get the tasks array updated to look like
[
{
"id": 1961126,
"tasks": [
{
**"sId":1961126,**
"id": 70340700,
"title": "Test1",
},
{
**"sId":1961126,**
"id": 69801130,
"title": "Test15A",
}
]
},
{
"id": 1961126,
"tasks": []
}
]
I can't figure out how to get the id from the object into the nested array. Here is what I have come up with
jq 'map(.tasks[0]|select( . != null )|.sId = .id)' file.json
This is only pulling in the same id. I have tired to put in [].id but I get a error Cannot index number with string "id". I am still learning how to deal with nested arrays and objects.
Save the ID in a variable and add it as a new field to each array member.
jq 'map(.id as $sId | .tasks[] += {$sId})' file.json
Demo
Note #1: Get rid of the final , within each object (see the Demo), as it's not proper JSON.
Note #2: Object fields generally have no order, but if you want to have the propagated ID shown first, as seen in your expected output, you could try to replace += {$sId} (which by itself is shorthand for |= . + {$sId}) with |= {$sId} + . to flip the order of generation (Demo). Although there is no guarantee that it stays that way with further processing.

Bash Parse JSON Objects jsawk

I´m trying to parse some JSON, which is the output of the Philips Hue API.
I found the tool jsawk, but somehow I´m not able to access the data inside the JSON Object.
The command:
... | jsawk 'return this.f709f9c0b-on-0.name'
works but unfortunately I don't have the ID of each object (e.g. f709f9c0b-on-0). Is there a way to access the object without knowing the ID and then to find out that ID. I tried to use "*" or Iterations of the objects but nothing was working.
Thanks in advance
The output looks like this:
{
"f709f9c0b-on-0": {
"name": "Badezimmer on 0",
"lights": [
"4"
],
"owner": "3e281978544fb15b42bc0e3a3f4ce3",
"recycle": true,
"locked": false,
"appdata": {},
"picture": "",
"lastupdated": "2016-02-17T17:20:06",
"version": 1
},
"69d313be0-on-0": {
"name": "Klavier on 0",
"lights": [
"1"
],
"owner": "3e281978544fb15b42bc0e3a3f4ce3",
"recycle": true,
"locked": false,
"appdata": {},
"picture": "",
"lastupdated": "2016-02-17T17:31:05",
"version": 1
},
...
}
f709f9c0b-on-0 is not a valid identifier due to the hyphens, so you can't use the dot notation. This might work (untested)
... | jsawk 'return this["f709f9c0b-on-0"].name'
I don't have jsawk, but jq can do it like this:
... | jq '.["f709f9c0b-on-0"].name'
Just for the rest of the world.
I solved the problem, by creating a .jar, which handles the problem. I find it much easier to do this in Java, than in bash.
I used this JSON-classes: https://github.com/stleary/JSON-java
Just download the files, create the package org.json and your good to go.
The Java Code, which worked for me is:
String JSON = "your JSON";
JSONObject jsonObject = new JSONObject(JSON);
ArrayList<ArrayList<String>> keyArray = new ArrayList<>();
Iterator<String> keys = jsonObject.keys(); //get all JSON keys
while (keys.hasNext()) { //for all keys do...
String key = (String) keys.next(); //get Current Key
//Now you can access the Object in the Object with:
jsonObject.getJSONObject(key).getString("name")
}
I hope this helps someone.

Format JSON file from 2 columns

I would like to create a JSON file for a Python script to parse.
My data is currently in a text file in the format of:
url1,string1
url2,string2
url3,string3
url4,string4
I would like to manually create a JSON file that I could input against a Python script to scrape for a string.
Thank you, I used your example to build something like it and it worked!
{"url": "url1", "string": "string1"} {"url": "url2", "string": "string2"} {"url": "url3", "string": "string3"}
Thanks
Something like the following should work
import csv
import json
csv_file = open('file.csv', 'r')
json_file = open('file.json', 'w')
field_names = ("url", "string")
reader = csv.DictReader(csv_file, field_names)
for row in reader:
json.dump(row, json_file)
json_file.write('\n')
I may misunderstand your question, if it's converting this CSV into a JSON manually, it would be :
[
[
"url1",
"string1"
],
[
"url2",
"string2"
],
[
"url3",
"string3"
],
[
"url4",
"string4"
]
]
If you prefer you can use CSV to JSON converter online

embed json file within d3.js

http://bl.ocks.org/mbostock/4339083 am using this
instead of d3.json("/d/4063550/flare.json", function(error, flare) {
how do i make it use the json file within the html, like say i have
var jsonData = [{
"name": "A",
"children": [
{"name": "A1", "children": [{"name": "A12"},{"name": "A13"},{"name": "A14"}] },
{"name": "A2", "children": [{"name": "A22"},{"name": "A23"},{"name": "A24"}] }
]
}];
and i want to use this instead of an external json file, how do i achieve this ?
Solution:
1.you can assign the JSON data to variable name then You can build the tree layout
2.use one function to get the JSON data
Fiddle for 1 solution
Fiddle for 2 solution
var root = getData(),
nodes = cluster.nodes(root),
links = cluster.links(nodes);

How to get a particular field from JSON in Ruby

I need to implement a simple shell utility in Ruby which parses JSON from a file and return a particular field from it.
JSON examples to be parsed:
{"status": "fail", "messages": ["Out of capacity"]}
{"status": "success", "messages": [], "result": {"node": {"ip": "1.2.3.4", "description": "", "id": 974, "name": "VM#3"}}}
Idea is to create a CLI utility with two parameters: JSON file to read and field from JSON to extract:
./get_json_field.rb ~/tmp.XXXXXX 'result.node.ip'
./get_json_field.rb ~/tmp.XXXXXX 'messages.0'
I'm struggling how to map 2nd parameter to parsed JSON data structure in Ruby. I can write an iterator for sure, splitting string to an array using dot as separator an go through it item by item but this doesn't look like elegant solution.
Any suggestions for more elegant way?
There is nothing wrong with splitting string and going through parts of it:
require 'json'
data1 = JSON.load('{"status": "fail", "messages": ["Out of capacity"]}')
data2 = JSON.load('{"status": "success", "messages": [], "result": {"node": {"ip": "1.2.3.4", "description": "", "id": 974, "name": "VM#3"}}}')
def get_from_json(data, query)
query.split('.').inject(data) do |memo, key|
key = key.to_i if memo.is_a? Array
memo.fetch(key)
end
end
get_from_json(data1, 'messages.0') # => "Out of capacity"
get_from_json(data2, 'result.node.ip') # => "1.2.3.4"
Take a look at jq it might already do what you are looking for.
jq .messages[0]
jq .node.message.ip
See http://stedolan.github.com/jq/