JSON Syntax: Transmitting an array - json

A valid JSON Syntax is something of the kind:
{
"username": "admin",
"password": "123"
}
But what if I want to transmit an array of 'users' (given the example), instead of a single 'user' ?
Is the code below Valid JSON, according to the specifications?
[{
"username": "admin",
"password": "123"
}, {
"username": "bbvb",
"password": "sdfsdf"
}, {
"username": "asd",
"password": "222"
}]
And if not, what is the best way to transmit an array of values across with JSON? (And with 'best way', I mean syntactically)

Yes, your example is valid JSON - that is exactly how you want to use an array.
Edit : Here is a good link on JSON and its usage.

The not-very-well-known page json.org has a diagram that shows the syntax. It’s extremely simple to understand, IMHO.

Json Syntax Includes following.
1. Data is represented in name/value pairs.
2. Each name is followed by ':'(colon).
3. The name/value pairs are separated by ,(comma).
4. Json object starts and ends with '{' and '}'.
5. Square brackets '[ ]' hold arrays and values are separated by
,(comma).
Json Objects Example
{
"id":"21",
"language": "Json",
"edition": "second",
}
Json Array Example
{
"book": [
{
"id":"21",
"language": "Json",
"edition": "second"
},
{
"id":"42",
"language": "Json",
"edition": "third"
}]
}
I have taken reference from http://www.tutsway.com/json-syntax.php

What you wrote up there is already correct :)
[{ "username" : "admin", "password" : "123" }, { "username" : "bbvb", "password" : "sdfsdf" }, { "username" : "asd", "password" : "222" }]

Related

NiFi EvaluateJSONPath loop through array to get correct value

here is an example of some JSON that I need to deal with:
{
"name": "John Smith",
"active": "yes",
"cpair": [
{
"title": "ADDRESS",
"charVal": "1234 Fulcrum lane"
},
{
"title": "phone",
"charVal": "555-7600"
}
]
}
So I'm using the evaluateJsonPath processor to add these values as attributes in my flowfile. thats easy for some. I can just set name equal to $.name and active to $.active. But lets say I need to give the attribute 'address' the value of "1234 Fulcrum lane". How do I assign that attribute the proper charVal value that matches up with the correct title?
according to Jayway JsonPath documentation
this should work:
$.cpair[?(#.title == 'ADDRESS')].charVal

How to add variables in json file?

Below is json file. I want to use variables for db password and db username. How can I add a variable in json ?
{
"name" : "mydb3",
"storage" : {
"binaryStorage" : {
"type" : "database",
"driverClass" : "com.mysql.jdbc.Driver",
"url" : "$jdbcdburl",
"username" : "$jdbcusername",
"password" : "$jdbcpassword"
}
},
"workspaces" : {
"default" : "default",
"allowCreation" : true
}
}
You can either build the JSON up using something like JSON Variables
https://www.npmjs.com/package/json-variables
Or you can load the JSON into memory look for the key and update it, example below using Node.JS
How to update a value in a json file and save it through node.js
Either way you wouldn't have to store the username and passwords in clear text, which is what I am guessing your are trying to avoid?
You may want to try Jsonnet, a data templating language, that is an extension of JSON and can export JSON files. E.g.
{
person1: {
username: "Alice",
password: "abc",
welcome: "Hello " + self.username + "!",
},
person2: self.person1 { username: "Bob", password: "123" },
}
would produce
{
"person1": {
"password": "abc",
"username": "Alice",
"welcome": "Hello Alice!"
},
"person2": {
"password": "123",
"username": "Bob",
"welcome": "Hello Bob!"
}
}
Other than fields you can also declare variables using local, e.g.
local pi = 3.14;
You can use string interpolation + backslash...
See "{{testUrl}}" in Postman exported JSON for exmaple:
Variable value:
"info":{
"_postman_id": "YOUR-ID-IN-POSTMAN",
"name": "YOU-EXPORTED-COLLECTION-FILE-NAME",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"testUrl": "https://www.techeader.com"},
Variable implemented in raw:
"url":{
"raw": "\"{{testUrl}}\"",
"protocol": "http",
"host": ["test","com"]},
JSON is a standard format for representing objects as a textual, human readable (most of the time :-/ ) format. The concept of a variable is not applicable in this context. Variables exist in memory/code only, and a variable can be written to JSON format in a file for example, but with the risk of sounding "blunt" IMHO, your question doesn't make much sense at this point.
If you elaborate a little more on what you want to achieve in your application, I might be able to help you better.

json schema for a map of similar objects

I wish to write a json schema to cover this (simplified) example
{
"errorMessage": "",
"nbRunningQueries": 0,
"isError": False,
"result": {
"foo": {"price":10.0, "country":"UK"},
"bar": {"price":100.2, "country":"UK"}
}
}
which can have this pretty trivial root schema
schema = {
"type":"object",
"required":True,
"properties":{
"errorMessage": {"type":"string", "required":True},
"isError": {"type":"boolean", "required":True},
"nbRunningQueries": {"type":"number", "required":True},
"result": {"type":"object","required":True}
}
}
The complication is the results {} element. Unlike a standard pattern where results would be an array of same objects - each with an id field or similar this response models a python dictionary which looks like this:
{
"foo": {},
"bar": {},
...
}
So given that a will be getting a results object of flexible size with no set keys how can I write json schema for this?
I don't control the input sadly or I'd rewrite it to be something like
{
"errorMessage": "",
"nbRunningQueries": 0,
"isError": False,
"result": [
{"id": "foo", "price":10.0, "country": "UK"},
{"id": "bar", "price":100.2, "country":"UK"}
]
}
Any help or links to pertinent examples would be great. Thanks.
With json-schema draft 4, you can use additionalProperties keyword to specify the schema of any new properties that you could receive in your results object.
"result" : {
"type" : "object"
"additionalProperties" : {
"type" : "number"
}
}
If you can restrict the allowed key names, then you may use "patternProperties" keyword and a regular expression to limit the permited key names.
Note that in json-schema draft 4 "required" must be an array which is bounded to the object, not to each property.

Customizing JSON output CakePHP

$user = $this->User->find( 'all' );
$this->set( 'users', $user );
I have this code in my controller.
In my view I have this.
echo json_encode( compact( 'users' ) );
It outputs json like this
{
"users": [{
"User": {
"user_id": "2",
"email": "email#test.com",
"name": "Blah"
}]
}
}
Is there anyway to format this to remove the entire array wrapped in "users", and also remove every object being a member of "User".
This makes it harder to use on the front end. I'd like it to look like this.
[{
"user_id": "2",
"email": "email#test.com",
"name": "Blah"
}]
Thanks for any help.
I don't fully understand what you mean by "remove the entire array wrapped in "users"" and "remove every object being a member of "User"", but according to your desired output format example, you'll need to extract and pass the exact data that you want to be encoded to json_encode, instead of passing everything using compact.
Extracting could be done with the Set or the Hash class (depending on your Cake version)
Assuming your model returns the data in the default CakePHP format, this for example:
json_encode(Set::extract('/User/.', $users));
should give you a structure like this:
[{
"user_id": "2",
"email": "email#test.com",
"name": "Blah"
}]
and with multiple users it should look like this
[{
"user_id": "1",
"email": "foo#test.com",
"name": "Bar"
},
{
"user_id": "2",
"email": "email#test.com",
"name": "Blah"
}]
Use like this:
$users= (Set::extract('/User/.', $users));
pr($users);
It will remove Model from result Array and then json_encode or whatever further usage.
More library functions Set class Here and Hash class Here

Jqgrid. How to handle server response before in will be passed to grid

I have a common structure of JSON data that come back from server, it contains some additional info about errors etc. How can I handle this data(check error info) and then pass only required data to grid.
This is JSON data structure:
{
"errorinfo": "foo",
"errormsg": "foo",
"errorCode": "foo"
"**jqgridData**": [
{
"total": "xxx",
"page": "yyy",
"records": "zzz",
"rows" : [
{"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
{"id" :"2", "cell":["cell21", "cell22", "cell23"]},
...
]
}
]
}
So I wand to process this JSON data and pass to grid only "jqgridData"
Thanks for help.
First of all the JSON data has one small error. The string
{ "errorinfo": "foo", "errormsg": "foo", "errorCode": "foo" "jqgridData": [ {
must be changed to
{ "errorinfo": "foo", "errormsg": "foo", "errorCode": "foo", "jqgridData": [ {
(comma between "errorCode": "foo" and "jqgridData" must be inserted). I hope the problem come during posting of the data in the question text only.
To your main question. The jsonReader allows you to read you practically any data. You data should be read with the following jsonReader:
jsonReader: {
root: "jqgridData.0.rows",
page: "jqgridData.0.page",
total: "jqgridData.0.total",
records: "jqgridData.0.records"
}
(where '0' element is needed as the index because of jqgridData is additionally an array).