I am implementing json API using Django Rest Framework.
Since sqlite is being used for database, json data is stored as string and when the data is requested, serializer parse the string and convert into json and sent to client side. This implementation worked for simple json file as shown in left picture. However, this cannot work for nested json as shown right picture.
Can anyone tell me how I should revise serializer in order to work for nested json also?
serializer.py
class strToJson(serializers.CharField):
def to_representation(self,value):
x=JSON.loads(value)
return x
class summarySerializer(serializers.ModelSerializer):
project=serializers.CharField(read_only=True,source="html.project")
version = serializers.CharField(read_only=True, source="html.version")
id = serializers.IntegerField(read_only=True, source="html.pk")
json = strToJson()
class Meta:
model=summary
fields=('id','project','version','json')
model.py
class summary(models.Model):
html = models.ForeignKey(html, on_delete=models.CASCADE,related_name='summaries')
keyword = models.CharField(max_length=50, default='test')
json = models.TextField(default='test')
I have JSON as a string and a JSONPath as a string. I'd like to query the JSON with the JSON path, getting the resulting JSON as a string.
I gather that Jayway's json-path is the standard. The online API, however, doesn't have have much relation to the actual library you get from Maven. GrepCode's version roughly matches up though.
It seems like I ought to be able to do:
String originalJson; //these are initialized to actual data
String jsonPath;
String queriedJson = JsonPath.<String>read(originalJson, jsonPath);
The problem is that read returns whatever it feels most appropriate based on what the JSONPath actually finds (e.g. a List<Object>, String, double, etc.), thus my code throws an exception for certain queries. It seems pretty reasonable to assume that there'd be some way to query JSON and get JSON back; any suggestions?
Java JsonPath API found at jayway JsonPath might have changed a little since all the above answers/comments. Documentation too. Just follow the above link and read that README.md, it contains some very clear usage documentation IMO.
Basically, as of current latest version 2.2.0 of the library, there are a few different ways of achieving what's been requested here, such as:
Pattern:
--------
String json = "{...your JSON here...}";
String jsonPathExpression = "$...your jsonPath expression here...";
J requestedClass = JsonPath.parse(json).read(jsonPathExpression, YouRequestedClass.class);
Example:
--------
// For better readability: {"store": { "books": [ {"author": "Stephen King", "title": "IT"}, {"author": "Agatha Christie", "title": "The ABC Murders"} ] } }
String json = "{\"store\": { \"books\": [ {\"author\": \"Stephen King\", \"title\": \"IT\"}, {\"author\": \"Agatha Christie\", \"title\": \"The ABC Murders\"} ] } }";
String jsonPathExpression = "$.store.books[?(#.title=='IT')]";
JsonNode jsonNode = JsonPath.parse(json).read(jsonPathExpression, JsonNode.class);
And for reference, calling 'JsonPath.parse(..)' will return an object of class 'JsonContent' implementing some interfaces such as 'ReadContext', which contains several different 'read(..)' operations, such as the one demonstrated above:
/**
* Reads the given path from this context
*
* #param path path to apply
* #param type expected return type (will try to map)
* #param <T>
* #return result
*/
<T> T read(JsonPath path, Class<T> type);
Hope this help anyone.
There definitely exists a way to query Json and get Json back using JsonPath.
See example below:
String jsonString = "{\"delivery_codes\": [{\"postal_code\": {\"district\": \"Ghaziabad\", \"pin\": 201001, \"pre_paid\": \"Y\", \"cash\": \"Y\", \"pickup\": \"Y\", \"repl\": \"N\", \"cod\": \"Y\", \"is_oda\": \"N\", \"sort_code\": \"GB\", \"state_code\": \"UP\"}}]}";
String jsonExp = "$.delivery_codes";
JsonNode pincodes = JsonPath.read(jsonExp, jsonString, JsonNode.class);
System.out.println("pincodesJson : "+pincodes);
The output of the above will be inner Json.
[{"postal_code":{"district":"Ghaziabad","pin":201001,"pre_paid":"Y","cash":"Y","pickup":"Y","repl":"N","cod":"Y","is_oda":"N","sort_code":"GB","state_code":"UP"}}]
Now each individual name/value pairs can be parsed by iterating the List (JsonNode) we got above.
for(int i = 0; i< pincodes.size();i++){
JsonNode node = pincodes.get(i);
String pin = JsonPath.read("$.postal_code.pin", node, String.class);
String district = JsonPath.read("$.postal_code.district", node, String.class);
System.out.println("pin :: " + pin + " district :: " + district );
}
The output will be:
pin :: 201001 district :: Ghaziabad
Depending upon the Json you are trying to parse, you can decide whether to fetch a List or just a single String/Long value.
Hope it helps in solving your problem.
For those of you wondering why some of these years-old answers aren't working, you can learn a lot from the test cases.
As of September 2018, here's how you can get Jackson JsonNode results:
Configuration jacksonConfig = Configuration.builder()
.mappingProvider( new JacksonMappingProvider() )
.jsonProvider( new JacksonJsonProvider() )
.build();
JsonNode node = JsonPath.using( jacksonConfig ).parse(jsonString);
//If you have a json object already no need to initiate the jsonObject
JSONObject jsonObject = new JSONObject();
String jsonString = jsonObject.toString();
String path = "$.rootObject.childObject"
//Only returning the child object
JSONObject j = JsonPath.read(jsonString, path);
//Returning the array of string type from the child object. E.g
//{"root": "child":[x, y, z]}
List<String> values = sonPath.read(jsonString, path);
Check out the jpath API. It's xpath equivalent for JSON Data. You can read data by providing the jpath which will traverse the JSON data and return the requested value.
This Java class is the implementation as well as it has example codes on how to call the APIs.
https://github.com/satyapaul/jpath/blob/master/JSONDataReader.java
Readme -
https://github.com/satyapaul/jpath/blob/master/README.md
I am using Mule 3.6.1 and in datamapper I have a JSON object which is a string datatype and I need to get the value of a field from the JSON object.
How can I get this value from the JSON object while the object is of type String?
I cannot use the JSON transformer for this.
Thanks for any help
To convert a String of JSON and get one of its field value inside DataMapper, then you can utilize code like this (in DataMapper Script area):
jsonObject = new org.json.JSONObject(input.jsonstring);
output.jsonValue = jsonObject.getString("jsonfield");
In order to convert JSON element to a series of objects. Google GSon library is very helpful.
Example:
import com.google.gson.Gson;
Gson gson = new Gson();
Student studentTest = gson.fromJson(data, Student.class);
System.out.println("Amount: " + studentTest .getStudentName());
What is the best way to retrieve data from JSON field in PostgreSQL using POCO framework?
The only way I see is:
Poco::Data::RecordSet rs(session, sql);
rs.moveFirst();
string value = rs[0].convert<std::string>(); // get JSON as string
Poco::JSON::Parser parser;
parser.parse(value);
Poco::Dynamic::Var result = parser.result();
// now we can extract Object, Array and so on
Direct extract
Poco::JSON::Object object = os[0].extract<Poco::JSON::Object>()
throws Can not convert [ERRFMT] to [ERRFMT] exception.
Any better solution?
Var result = parser.parse(value);
Object::Ptr object = result.extract<Object::Ptr>();
I use solrj to submit a query to solr , that returns the result in json format.
SolrQuery query = new SolrQuery();
SolrQuery query = new SolrQuery();
query.setParam("kw", keyword);
query.setParam("lc", location);
query.setParam("wt", "json");
query.setParam(CommonParams.QT, "/lds");
QueryResponse qResponse = solrServer.query(query);
searchResultStr = qResponse.toString();
But the searchResultStr does not have a string in JSON format. Instead it has something like this:
{responseHeader={status=0,QTime=21},location={has_zipcode=true,location_param=94085}}
But if i directly hit the solr url in the browser, I get the correct JSBON format:
{"responseHeader":{"status":0,"QTime":15},"location": {"has_zipcode":true,"location_param":"94085"}}
For a JSON output you will have to query a HTTPSolrServer using curl as mentioned in the answer here. Using EmbeddedSolrServer will not help i.e. solrj.
When you use solrj to query you will have to get the SolrDocumentList from the QueryResponseobject and convert it into JSON format by iterating through each SolrDocument and entering the data into JSON the way you want.
Solr QueryResponse returns a hashmap, so use any hashmap to json converter to get the json out of it. Here I have used Gson() for that conversion.
QueryResponse response = solr.query(query);
Gson gson = new Gson();
String json = gson.toJson(response.getResults());
System.out.println(json);