Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to write a program which can create an output in JSON format, how would be best way of doing this? and programming languages?
This is an example output of JSON (expected output) which I need to input in the Name, Gender, Qualification and other attributes in a user friendly way during the execution of script. And in which outputs in following JSON format. Sorry, I am new in programming, but so much interested to learn Perl (or) Python (or) Java. What could be the best here?
Any suggestions?
P.S Sorry I am quite new to JSON as well, please apologize me for this basic one.
[
{
"Name":"Steven Mark",
"gender":"male",
"Qualification": {
"college":"Bachelor in Science",
"tech":"certified pro"
},
"contributions": [
{
"name":"biography",
"type":"book",
},
]
},
{
"Name":"Andrea Mark",
"Gender":"female",
"Qualifications": {
"college":"Bachelor in physics",
},
"contributions": [
{
"name":"my insights",
"type":"movie",
},
]
}
]
Virtually every language has a JSON library, including Perl.
use JSON;
my $data = [
{
"Name" => "Steven Mark",
"gender" => "male",
"Qualification" => {
"college" => "Bachelor in Science",
"tech" => "certified pro"
},
"contributions" => [
{
"name" => "biography",
"type" => "book",
},
]
},
{
"Name" => "Andrea Mark",
"Gender" => "female",
"Qualifications" => {
"college" => "Bachelor in physics",
},
"contributions" => [
{
"name" => "my insights",
"type" => "movie",
},
]
}
];
print(encode_json($data));
If you agree to use ANY programming language, i can suggest python. With its json lib you can do following (lines with # is comments):
# import lib
import json
# fill data into variable (this is list with dict objects inside):
data = [{"name":"john"},{"name": "bill"}]
# dump json
json.dumps(data)
Which will output your data as json.
You can start writing python using something from https://wiki.python.org/moin/BeginnersGuide
If you are going to use Python, you can try to use simplejson or json module to create a json object.
For example,
try:
import simplejson
except:
import json
data = dict(a=1,b=2)
with open("results.json", "w") as fp:
json.dump(data, fp, indent=3, encoding="utf-8")
For dumping, json is faster than simplejson (but not by an order of magnitude). For loading, simplejson is faster (but not by an order of magnitude).
You can check here for more detailed comparison between simplejson and json.
Related
I've tried a few different way of doing this. I have a JSON string that I'm parsing with JSONSlurper that looks like this, and I want to get the value with a key==StoreID2.
{
"EmailData": {
"MessageRecords": [
{
"To": "this#that.com",
"FieldData": [
{
"key": "StoreName",
"value": "Livonia"
},
{
"key": "StoreID2",
"value": "7017"
}
]
}
]
}
}
With JSONPath I can get the value like this: $.EmailData.MessageRecords[0].FieldData[?(#.key=="StoreID2")].value But it doesn't look like Groovy has JSONPath available, without loading a non-native library (com.jayway.jsonpath.JsonPath.parse), which I'm trying to avoid.
This is actually the solution:
def jsonSlurper = new JsonSlurper();
def jsonObject = jsonSlurper.parseText(inputSB.toString());
logger.info("Store: " + jsonObject.EmailData.MessageRecords[0].FieldData.find{it.key=='StoreID2'}.value);
Thanks
Though I could see this question might be repeated but couldn't find any similar solution for the below JSON strut. Pls suggest.
I have excel sheet where the data's in columns look like :
CSV file data
My expected JSON as:
{
"Child ": {
"10"
: { "Post": { "Kid-R":1 },
"Var": [1,1 ],
"Tar": [2,2],
"Fur": [3,3]},
"11":
{"Post": {"Kid-R":2 },
"Var": [1,1 ],
"Tar": [2,2 ],
"Fur": [5,4 ]}
},
"Clone": [],
"Birth": 2,
"TT": 11,
"Clock": ${__time(/1000,)}
}
I have tried incorporating beanshell preprocessor in JMeter & tried below code:
def builder = new groovy.json.JsonBuilder()
#groovy.transform.Immutable
class Child {
String post
String var
String Tar
String Fur
}
def villas = new File("Audit_27.csv")
.readLines()
.collect { line ->
new child (line.split(",")[1],(line.split(",")
[2]+","+line.split(",")[3]),(line.split(",")[4]+","+line.split(",")
[5]),(line.split(",")[6]+","+line.split(",")[7]))}
builder(
Child :villas.collect(),
"Clone": [],
"Birth": 2,
"TT": 11,
"Clock": ${__time(/1000,)}
)
log.info(builder.toPrettyString())
vars.put("payload", builder.toPrettyString())
And I could see below response only:
Note: I dont know how to declare "Key" value (line.split(",")[0]) in the above solution.
{
"Child": [
{
"post": "\"\"\"Kid-R\"\":1\"",
"var": "\"[2,2]\"",
"Tar": "\"[1,1]\"",
"Fur": "\"[3,3]\""
},
{
"post": "\"\"\"Kid-R\"\":2\"",
"var": "\"[2,2]\"",
"Tar": "\"[1,1]\"",
"Fur": "\"[3,3]\""
}
],
"Clone": [],
"Birth": 2,
"TT": 11,
"CLock": 1585219797
}
Any help would be greatly appreciated
You're copying and pasting the solution from this answer without understanding what you're doing.
If you change class name from VILLA to own you need to use new own instead of new VILLA
Also this line won't compile: Clock: <take system current time> you need to use System.currentTimeMillis() or appropriate function of the Date class in order to generate the timestamp.
If you want a comprehensive answer, you need to provide:
Well-formatted CSV file
Valid JSON payload
In the meantime I would recommend getting familiarized with the following material:
Apache Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
Reading a File in Groovy
Actually I am gonna follow DmirtiT suggestions, as mentioned in some of post to use random variable for bulk API request. Same answer it helped me here as well to generate multiple JSON structure with unique data. Thanks..
I have the following entry in MarkLogic in JSON format:
{
"identifier":"user1",
"attributesList": [
{
"firstName": "James",
"address_1": "Farcity"
}
]
}
If, I'm going to query that using the below format:
{
$query:
{
"identifier":"user1",
"attributesList": [
{
"firstName": "James"
}
]
}
}
this will match and return back the expected result with a count of 1 because "firstName" is equal to "James".
However, if I do the following:
{
$query:
{
"identifier":"user1",
"attributesList": [
{
"address_1": "Farcity"
}
]
}
}
it will not give back any result even if "address_1" exactly matches which is "Farcity". I already tried this on other JSON key as well, it works fine with all except those with underscores in the key.. Is this a reserved character? If so, is there a way to escape this so that the key "address_1" or "county_state" can still be matched?
It looks like the Json object converts the underscores to a double underscore
running this:
xquery version "1.0-ml";
import module namespace json="http://marklogic.com/xdmp/json"
at "/MarkLogic/json/json.xqy";
let $j :=
'{
"identifier":"user1",
"attributesList": [
{
"firstName": "James",
"address_1": "Farcity"
}
]
}'
return
json:transform-from-json( $j)
you will get this out put
<json type="object" xmlns="http://marklogic.com/xdmp/json/basic">
<identifier type="string">user1</identifier>
<attributesList type="array">
<json type="object">
<firstName type="string">James</firstName>
<address__1 type="string">Farcity</address__1>
</json>
</attributesList>
</json>
So try querying with a double underscores. Also If you are using Marklogic 6 or 7 it converts the Json to xml. so you could just try to query by example using the XML format.
See http://docs.marklogic.com/xdmp:encode-for-NCName for the exact algorithm and function used to map JSON field names to QNames
I am using Java API for CRUD operation on elasticsearch.
I have an typewith a nested field and I want to update this field.
Here is my mapping for the type:
"enduser": {
"properties": {
"location": {
"type": "nested",
"properties":{
"point":{"type":"geo_point"}
}
}
}
}
Of course my enduser type will have other parameters.
Now I want to add this document in my nested field:
"location":{
"name": "London",
"point": "44.5, 5.2"
}
I was searching in documentation on how to update nested document but I couldn't find anything. For example I have in a string the previous JSON obect (let's call this string json). I tried the following code but seems to not working:
params.put("location", json);
client.prepareUpdate(index, ElasticSearchConstants.TYPE_END_USER,id).setScript("ctx._source.location = location").setScriptParams(params).execute().actionGet();
I have got a parsing error from elasticsearch. Anyone knows what I am doing wrong ?
You don't need the script, just update it.
UpdateRequestBuilder br = client.prepareUpdate("index", "enduser", "1");
br.setDoc("{\"location\":{ \"name\": \"london\", \"point\": \"44.5,5.2\" }}".getBytes());
br.execute();
I tried to recreate your situation and i solved it by using an other way the .setScript method.
Your updating request now would looks like :
client.prepareUpdate(index, ElasticSearchConstants.TYPE_END_USER,id).setScript("ctx._source.location =" + json).execute().actionGet()
Hope it will help you.
I am not sure which ES version you were using, but the below solution worked perfectly for me on 2.2.0. I had to store information about named entities for news articles. I guess if you wish to have multiple locations in your case, it would also suit you.
This is the nested object I wanted to update:
"entities" : [
{
"disambiguated" : {
"entitySubTypes" : [],
"disambiguatedName" : "NameX"
},
"frequency" : 1,
"entityType" : "Organization",
"quotations" : ["...", "..."],
"name" : "entityX"
},
{
"disambiguated" : {
"entitySubType" : ["a", "b" ],
"disambiguatedName" : "NameQ"
},
"frequency" : 5,
"entityType" : "secondTypeTest",
"quotations" : [ "...", "..."],
"name" : "entityY"
}
],
and this is the code:
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(indexName);
updateRequest.type(mappingName);
updateRequest.id(url); // docID is a url
XContentBuilder jb = XContentFactory.jsonBuilder();
jb.startObject(); // article
jb.startArray("entities"); // multiple entities
for ( /*each namedEntity*/) {
jb.startObject() // entity
.field("name", name)
.field("frequency",n)
.field("entityType", entityType)
.startObject("disambiguated") // disambiguation
.field("disambiguatedName", disambiguatedNameStr)
.field("entitySubTypes", entitySubTypeArray) // multi value field
.endObject() // disambiguation
.field("quotations", quotationsArray) // multi value field
.endObject(); // entity
}
jb.endArray(); // array of nested objects
b.endObject(); // article
updateRequest.doc(jb);
Blblblblblblbl's answer couldn't work for me atm, because scripts are not enabled in our server. I didn't try Bask's answer yet - Alcanzar's gave me a hard time, because I supposedly couldn't formulate the json string correctly that setDoc receives. I was constantly getting errors that either I am using objects instead of fields or vice versa. I also tried wrapping the json string with doc{} as indicated here, but I didn't manage to make it work. As you mentioned it is difficult to understand how to formulate a curl statement at ES's java API.
A simple way to update the arraylist and object value using Java API.
UpdateResponse update = client.prepareUpdate("indexname","type",""+id)
.addScriptParam("param1", arrayvalue)
.addScriptParam("param2", objectvalue)
.setScript("ctx._source.field1=param1;ctx._source.field2=param2").execute()
.actionGet();
arrayvalue-[
{
"text": "stackoverflow",
"datetime": "2010-07-27T05:41:52.763Z",
"obj1": {
"id": 1,
"email": "sa#gmail.com",
"name": "bass"
},
"id": 1,
}
object value -
"obj1": {
"id": 1,
"email": "sa#gmail.com",
"name": "bass"
}
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 9 years ago.
Iam new to java script and JSON, please help me in solving my problem. Below is the structure of my JSON in JavaScript
{
"name": "sample",
"def": [
{
"setId": 1,
"setDef": [
{
"name": "ABC",
"type": "STRING"
},
{
"name": "XYZ",
"type": "STRING"
}
]
},
{
"setId": 2,
"setDef": [
{
"name": "abc",
"type": "STRING"
},
{
"name": "xyz",
"type": "STRING"
}
]
}
]
}
in the backend, what should be the synatx of java method to receive this data
public void getJsonData(****){
}
How to parse this JSON data in java and what should be the syntax of method parameter ?
update 1: Edited the json format to make it valid
First create a class that will map your json object and give a name something like "DataObject". Then use the gson library and do the following:
String s = "";
DataObject obj = gson.fromJson(s, DataObject.class);
Your JSON is invalid, but assuming you fix that then you are looking for a library in Java which will serialize an annotated Java class to JSON, or deserialize JSON data to an annotated Java class.
There is a whole list of suitable libraries here:
http://json.org/java/