I want to extract id value from this json data. I tried many ways but I don't know what went wrong in my code also I wnt to store id into an array
JSONObject json = readurl("https://graph.facebook.com/"+s);
System.out.println(json);
String json2=json.getString("likes");
{"data":[
{
"id":"**********",
"name":"skkjghkjhkj"
},
{
"id":"********",
"name":"khkfjhkjf"
}
]
I'm not pretty sure if this is the right answer or maybe I've misread the question, but as said in the question extracting the id from data could be done by:
syso(json2.data[i].id)
i=0 -> n
basically your JSON contains an array in it, so you would access it like any other array!
Source: w3schools Stackoveflow
Related
I am stuck in a problem where I have to filter json data from a String which is a combination of json string and normal text.
sample: This message has all your required detail { "name" : "xyz","age": "21","place" :"sdf", "number": "7689"} check in this page you will get the details.
I need to extract the json object from given string.
Result expected is only : { "name" : "xyz","age": "21","place" :"sdf", "number": "7689"}.
Is there any clean way of doing this in Java.
One way to solve this is to remove non-json string and extract json object.
But that is a bad approach in my view.
If there are no other JSON-like parts, you can just extract the part between the first { and last }, including both ends:
int start=str.indexOf('{');
int end=str.lastIndexOf('}');
String json=str.substring(start,end+1);
Then of course you may want to check if both start and end are non-negative (so the characters are actually present), if there is a possibility that the string does not contain anything for you.
Also note that JSON can be an array too, so you can try checking if a pair of first [ and last ] lies outside of the {...}, but then at the end single values are valid JSON too (like true, false, 1, etc.). This is not really a happy task to write properly, thinking of everything.
First time having to work with JSON data on my own, even if very simple.
Here is the JSON data I'm working with:
{
"heart" : [92, 108],
"temperature" : [85.08, 85.66],
"conductance" : [4095, 4095]
}
What I'm attempting to do is extract one of the three arrays found within that JSON object, but I'm receiving a JSONException: Not a primitive array: class org.json.JSONArray. Here is a portion of the code that I'm using to extract the array of values associated with "heart":
JSONObject obj = new JSONObject(obtainJSONObject());
JSONArray arr = new JSONArray(obj.getJSONArray("heart")); // This is where the error is occuring
int low = arr.getInt(0);
int high = arr.getInt(1);
I've tried to follow what this solution answered, but can't really make much sense of it: How to Get JSON Array Within JSON Object?
I'm not sure if it has something to do with the way how the JSON data is being formatted? I did check online to see if it was any valid or not at https://jsonformatter.curiousconcept.com/. Any help or insights will be greatly appreciated!
I have a text file which contains a line like
players={"Messi":{"Details":{"Goals":500},"Country":"Argentina"},"Neymar":{"Clubs":["Santos", "FC barcelona", "Paris saint German"], "Country":"Brazil"}}
Now I am used a regex for extract the
{"Messi":{"Details":{"Goals":500},"Country":"Argentina"},"Neymar":{"Clubs":["Santos", "FC barcelona", "Paris saint German"],"Country":"Brazil"}}
from the text file and pass it in to a case class which accepts the value as a String.
and I am making a Dataframe using this case class.
In my case every line may be different in the contents with in the JSON String.So I am looking for a general solution to Convert any complex Json string to Map values.
When checking dataframe.printSchema, I am getting the players column as a String type.
But I need it to be as a Map type which holds a Key and value as a Struct type.
I tried method referred in this link
How can I convert a json string to a scala map?
when I used this way,I got error
"org.json4s.package$MappingException: Do not know how to convert JObject(List((Details,JObject(List((Goals,JString(500))))), (Country,JString(Argentina)))) into class java.lang.String "
and I used following solutions
Converting JSON string to a JSON object in Scala
But these too won't worked for me.
This is my case class
case class caseClass (
Players :String = ""
)
I am Extracting the json string using a user defined function.
Simply my requirement is that I have a complex Json String which contains keys and values as struct,list etc..
so I want to make the string to its corresponding JSON which holds a proper schema with respect to its contents.
Kindly expecting Valuable solutions.
If you also can live with JsValue as value instead of String it looks a bit simpler:
import play.api.libs.json._
case class CaseClass (
Players :Option[JsValue]
)
object CaseClass {
implicit val jsonFormat = Json.format[CaseClass ]
}
I saw some problems with your Json - so you would need to have something like:
val json = Json.parse("""{
"Players":{
"Messi":{"Details":{"Goals":500},"Country":"Argentina"},
"Neymar":{"Clubs":["Santos", "FC barcelona", "Paris saint German"], "Country":"Brazil"}
}
}"""
)
To get a String out of this you can use:
json.validate[CaseClass] match {
case JsSuccess(cc, _) => cc.Players.toString
case JsError(errors) => // handle errors
}
I got another solution which I think More easier.
I Made an own schema for the JSON and Used from_json method with the schema,and it worked well.
from_json(col("Players"),ownschema).as("new_Json")
and my ownschema contains the structure of the Json String.
For any doubts, Comment.
Happy Coding.
I have a JSON String stored in a database. In one of my JSP pages, I retrieve this string, and I want to be able to pass the String or the JSON object into Javascript function. The function is simply this for test purposes
function test(h){
alert(h);
}
Now I can retrieve the JSON string from the database fine, I have printed it out to the screen to ensure that it is getting it, however when I pass it in like this
<input type="button"
name="setFontButton"
value="Set"
class="form_btn_primary"
onclick="test('<%=theJSON%>'); return false;"/>
Nothing happens. I used firebug to check what was wrong, and it says there is invalid character.
So I then tried passing in the JSON object like so
Widget widg = mapper.readValue(testing.get(0), Widget.class);
Then pass in it
onclick="test('<%=widg%>'); return false;"/>
Now this will pass in without an error, and it alerts the object name, however I am unable to parse it. Object comes in like with the package name of where the widget class is stored like so
com.package.mode.Widget#ba8af9
I tried using Stringify, but that doesn't seem to work on this Jackson JSON object.
After all that failed, I tried a last resort of taking the String from the database, and encoding it in base64. However, this too fails if I do this
String test = Base64.encode(theString);
and pass that in. However if I do that, print it out to the screen, then copy what is printed out, and send that through it works, so don't quite understand why that is.
So could someone please tell me what I am doing wrong. I have tried soo many different solutions and nothing is working.
The JSON String is stored in database like this
{
"id":1,
"splits":[
{
"texts":[
{
"value":"Test",
"locationX":3,
"locationY":-153,
"font":{
"type":"Normal",
"size":"Medium",
"bold":false,
"colour":"5a5a5a",
"italics":false
}
}
]
}
]
}
Would be very grateful if someone could point me in the direct direction!!
Edit:
Incase anyone else has same problem do this to pass the JSON from JSP to the JS function
<%=theJSON.replaceAll("\"", "\\\'")%>
That allows you to pass the JSON in,
then to get it back in JavaScript to normal JSON format
theJSON = theJSON.replace(/'/g,'"');
Should work fine
I think the combination of double quotes wrapping the onclick and the ones in your JSON may be messing you up. Think of it as if you entered the JSON manually -- it would look like this:
onclick="test('{ "id":1, "splits":[ { "texts":[ { "value":"Test", "locationX":3, "locationY":-153, "font":{ "type":"Normal", "size":"Medium", "bold":false, "colour":"5a5a5a", "italics":false } } ] } ] }'); return false;"
and the opening double quote before id would actually be closing the double quote following onclick= (You should be able to verify this by looking at the page source). Try specifying the onclick as:
onclick='test(\'<%=theJSON%>\'); return false;'
You can follow the following steps
Fetch the jon string
Using the jackson or any other JSON jar file , convert the json string to json array and print the string using out.println.
Call this jsp which prints the json string
check in the firebug , you will be able to see your json .
If the Json string does not print , there can be some problems in your json format.
this is a good website for json beautification , http://jsbeautifier.org/ , really makes the string simple to read .
Thanks
Abhi
Hey,
Im trying to parse the following JSON data:
{"chat":
{"link":
[{"#rel":"next","#ref":"http"}],
"events":
{"link2":
[{"#rel":"next","#ref":"http"}]}
}}
The code that reads the data is (where 'a' is the JSON as String):
JSONObject jsonObject1 = new JSONObject(a);
JSONObject jsonObject = jsonObject1.getJSONObject("chat");
So the structure (at least the way I intended) is:
<chat>
<link>
<events>
<link2>
</events>
</chat<
But, after getJsonObject("chat"), jsonObject equals to:
{"chat":{"events":{"link2":[{"#ref":"http","#rel":"next"}]},"link":[{"#ref":"http","#rel":"next"}]}}
What am I missing? Why does the data flips and the structure changes?
The properties in a JSON object are not sorted. From the JSON site:
An object is an unordered set of name/value pairs...
(My emphasis) Therefore the position of link and event are irrelevant for the parser. Bottom line, link and event are at the same level therefore they can be shifted and wherever order matters use arrays in JSON ... [].