w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Perl hash to json conversion?
The first four lines in Mojo::JSON's SYNOPSIS will tell you. use Mojo::JSON; my $json = Mojo::JSON->new->encode( $VAR1 );

Categories : Json

Hex conversion in Perl
You do not need to add the 0x part, and you can use zeros to justify: sprintf "%#05x", 35; # 0x023 Documentation here. Note that the "number of zeros" to justify is 5 here and not 3 as one might think.

Categories : Perl

Conversion from DataSet to JSON ends up wrapping the JSON string with xml tags
I didn't find any good way to return pure JSON from WCF project nor ASMX despite all "Experts" saying "its easy" Add web page to your project (ASPX) which can use your web service as data source and then to serialize the objects from the web service JSON. By using: JavaScriptSerializer serializer = new JavaScriptSerializer(); String myJSON= serializer.Serialize(<your object>); And "myJSON" will hold the JSON. The JavaScriptSerializer can't handle DataTableDataSet so what you can do is to insert DataSet into DataTable and use the following method to convert it to JSON (string) public static string GetDataTableToJSONString(DataTable table) { List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

Categories : C#

How to let Newtonsoft.Json allow Json DateTime conversion with Timezone info?
I think this link should help you with setting up MVC3 project working with Newtonsoft Json Serializer. For ISO date time formatter you should change the following lines in the JsonNetResult constructor. public JsonNetResult() { Formatting = Formatting.None; var settings = new JsonSerializerSettings(); settings.Converters.Add(new IsoDateTimeConverter()); SerializerSettings = settings; JsonRequestBehavior = JsonRequestBehavior.DenyGet; } You have to derive your controllers from BaseController to use the custom result. hope this helps.

Categories : Json

Issue with conversion from XML to JSON with json or json-lib
Try using the library from www.json.org instead of net.sf.json.JSON import org.json.JSONObject; import org.json.XML; String xmlString = "<detail>&lt;P&gt;Students should avoid purchasing their textbooks at the first store that they browse. Instead, they should investigate the alternatives offered by other online booksellers. Price isn't the only factor to consider when making an online purchase. Students should also factor in shipping costs and delivery time when making their buying decision.&lt;/P&gt;</detail>"; System.out.println("Initial XML : " + xmlString); JSONObject jsonObj = (XML.toJSONObject(xmlString)); System.out.println("Converted JSON : " + jsonObj.toString()); System.out.println("Back to converted XML : " + XML.toString(jsonObj)); You'll get th

Categories : Java

Custom JSON to XML conversion using JSON.Net
Internally, Json.Net uses a special JsonConverter called XmlNodeConverter to do the conversion from JSON to XML or vice-versa. This converter does not seem to be very extensible as it is, but you could create your own custom converter using the XmlNodeConverter source code as a starting point, then plug that back into Json.Net. XmlDocument doc = JsonConvert.DeserializeObject<XmlDocument>(json, yourCustomXmlNodeConverter);

Categories : C#

Error while CSV-JSON conversion
JSON.parse is not present in outdated browsers, most notably, IE7. You're getting that error because the browser is not providing you with window.JSON. Because of this, you're using json2.js. However, github does not want you hotlinking to files, and so serves it as text/plain. This causes the browser not to interpret it as a script, so it never executes, and no JSON object is provided. You need to host json2.js yourself, or find and use a CDN.

Categories : Javascript

HTML to JSON conversion in xslt
If you want to change the namespace of your elements (from the XHTML namespace to no namespace), then you can't use xsl:copy-of, which copies them unchanged; you need to use a recursive template that reconstructs each element: <xsl:template match="*" mode="no-ns"> <xsl:element name="{local-name()}"> <xsl:copy-of select="@*"/> <xsl:apply-templates mode="no-ns"/> </xsl:element> </xsl:template>

Categories : HTML

conversion from string to json object android
Remove the slashes: String json = {"phonetype":"N95","cat":"WP"}; try { JSONObject obj = new JSONObject(json); Log.d("My App", obj.toString()); } catch (Throwable t) { Log.e("My App", "Could not parse malformed JSON: "" + json + """); }

Categories : Android

WSO2 ESB Version 4.7.0, Simple JSON to XML conversion issue
I tested your scenario and I get the correct output as follows. <kind>plus#person</kind> Following is my proxy service. <?xml version="1.0" encoding="UTF-8"?> <proxy xmlns="http://ws.apache.org/ns/synapse" name="MockJsonTest" transports="https,http" statistics="disable" trace="disable" startOnLoad="true"> <target> <inSequence> <property name="messageType" value="text/xml" scope="axis2" type="STRING"/> <property name="ContentType" value="text/xml" scope="axis2" type="STRING"/> <log level="full"/> <property name="OUT_ONLY" value="true" scope="default" type="STRING"/> <property name="transport.vfs.ReplyFileName" value="

Categories : Xml

complex json to java object conversion using gson
You need a class structure like this (pseudo-code): class Response String id DataList posts class DataList List<Data> data class Data String message From from String id String created_time DataList comments class From String name String id Note that you can change class names if you want, but you have to keep the attribute names to match the field names in the JSON response. Also note that I've used the same class Data to store the data for the posts and for the comments. This is possible because the data for comments is a subset of the data for posts, so when parsing a comment, Gson will just ignore the attributes created_time and comments... Then parse the JSON with: Gson gson = new Gson(); Response response = gson.fromJson(yourJsonString, Response.clas

Categories : Java

Newtonsoft JSON- Conversion to/from DataSet causes Decimal to become Double?
I suspect it has something to do with the standard (XML) serialization of DataSet and DataTable. If you write DataSet from the example to a file you'll see that information about the DataTable schema isn't provided. This can be determined when reading the XML file back into a table. The data from your example written to a file gives this result: <NewDataSet> <Table1> <Test>1.23345</Test> </Table1> </NewDataSet> When the DataSet with the DataTable has been read you can't change the type of the column (in my test case when going to/from XML the type is string) but you can .Clone() the DataTable and move/convert the data: var clonedTable = ds.Tables[0].Clone(); clonedTable.Columns[0].DataType = typeof(decimal); foreach (DataRow row in dt.Table

Categories : C#

conversion of array list to json object string
Don't bother with org.json, use Jackson all the way: // list is a List<MyData> final ObjectMapper mapper = new ObjectMapper(); final Map<String, MyData> map = new HashMap<>(); for (final MyData data: list) map.put(data.fname, data); final JsonNode json = mapper.valueToTree(map);

Categories : Java

Complex Python JSON object to custom dictionary conversion
Sometimes when operating on nested structures using recursive functions, its easier to think in terms of a walking function and an operation function. So we want to target all the dicts contained in the json structure and perform a transformation operation on them. Transforming a structure in-place, instead of recreating a new one, is significantly easier when dealing with nests. The more difficult approach of constructing nested dicts from that json structure involves being able to address the specific json elements, place them at correct depth and branch of the new structure; this involves two parallel walking operations. One thing to be mindful of though, is modifying the nested structure while walking across it as a transformation operation may change a list that the walking function

Categories : Python

Python conversion of JSON object to pandas from an API streaming data
Seems your getCalendar is writing stuff to stdout and you first need to capture that into a string variable. Use this post solution to capture: Can I redirect the stdout in python into some sort of string buffer? (e.g. write a wrapper like getCalendarStdout() used below) Once you got the json output into a variable (say calendar), try this: calendar = getCalendarStdout() import json import pandas as pd data=json.loads(calendar) dafr = pd.DataFrame(data,columns=['col1','col2']) Here we are trying to get only certain fields from the json output into the dafr DataFrame. If you can paste the calendar json data (part of it) people can help you get desired dataframe.

Categories : Python

GSON - the Array<>Object JSON-Conversion is not solved despite TypeAdapter
I myself find your code a bit messy, so I can't really find the error. I'll explain what I'd do from the beginning and maybe you can compare it with your code and get some ideas... First I'd create these 2 classes: class Response List<Element> element; class Element String id; String subtitle; String name; String subline; String count; Then I'd create a TypeAdapter, and I think the easiest way is to create one for the Responseclass. Something like: public class ResponseDeserializer implements JsonDeserializer<Response> { public Response deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) { JsonElement elementField = json.getAsJsonObject().get("element"); List<Element> elementList = new ArrayLis

Categories : Java

Conversion required for part of an html code that is in JSON format
You can parse comments from an html using lambda text:isinstance(text, Comment), then load the json string via json module. Here's an example: import json from bs4 import BeautifulSoup, Comment soup = BeautifulSoup(""" <table> <tr> <td><table><tr><td>1</td></tr><tr><td>2</td></tr></table></td> </tr> <!-- {"test": [1,2,3]} --> <tr> <td><table><tr><td>3</td></tr><tr><td>4</td></tr></table></td> </tr> </table> """) comments = soup.find(text=lambda text:isinstance(text, Comment)) comments = json.loads(comments) print comments['test'] prints: [1,2,3] Hope that helps.

Categories : Python

xml to json conversion issue in java, 1st leading zero discarded fom string
looking at the code for XML.java - in particular the stringToValue method which does "Try to convert a string into a number, boolean, or null". The code is below - you can see it tries to parse as a number first, in which case it will trim the leading zeros. To test you could try adding a non-numeric character in your string - I think it would then preserve the leading zeros. It looks like the behaviour you're seeing is baked into the library. Which is not great, even though the docs for the function toJSONObject do warn "Some information may be lost in this transformation because JSON is a data format and XML is a document format" teh codez : // If it might be a number, try converting it. If that doesn't work, // return the string. try { char initial = st

Categories : Java

If JSON contains $myid then (Perl)
The bind operator =~ treats its LHS as a string and the RHS as a pattern. The stringification of an arrayref looks like ARRAY(0x12ABF14), so this isn't useful. We have two possibilities to match the $myid against each member of the array: The grep EXPR, LIST builtin. Selects all elements where the expression returns a true value. If the count of the returned items is ≥ 1, then a matching element was found. if ( grep $myid eq $_, @{ $card->{idMembers} }) { do stuff } # or: grep /Q$myid/, ... if you don't want string equality Use the smartmatch operator ~~ in the member-of meaning: if ( $myid ~~ $card->{idMembers} ) { do stuff } This is subjects to multiple caveats: (1) It is only usable since v10.1. Therefore, code using smartmatch should at least use 5.010001. (2) Smartmatc

Categories : Json

Apache Camel - Json to POJO automatic data type conversion?
Yes, this can be achieved with TypeConverters http://camel.apache.org/type-converter.html You can also perform this explicitly with the dataFormats element too http://camel.apache.org/data-format.html Hope that helps :)

Categories : Java

speeding up JSON parsing in Perl
Try to install JSON::XS. Then, "use JSON" automatically uses the XS version. This module was written in C, and it has a very good performance.

Categories : Json

Passing Json from Angular to Perl
Thank you all for responding. I found the solution. First I included JSON library. Then the following did the trick: if ($ENV{'REQUEST_METHOD'} eq "POST") { my $in; my $got = read(STDIN, $in, $len); my $decoded = decode_json($in); print "Name = " . $decoded->{'name'}; } Again, thank you all for responding.

Categories : Json

create a json string in perl
What you need is a hash reference: use strict; use warnings; use JSON; my $json = JSON->new; my $data_to_json = {d=>{success=>JSON::false,error=>"key is required"}}; print $json->encode($data_to_json) . " "; The output is: {"d":{"success":false,"error":"key is required"}} Note the use of JSON::false to denote a value that the JSON module will correctly translate to false as a JSON value.

Categories : Json

How do I parse a 3D JSON array in Perl?
If you had turned on use strict and use warnings, which you should always do, you would have gotten a bunch of fatal errors about undeclared variables. Let's fix those first: use strict; use warnings; use JSON; my $test='{ "name":"Tony", "body":[ { "arms":["hands:fingers", "muscles:biceps"], "stomach":["abs:sixpack", "noabs:onepack"] }, { "arms":["fingers:nails", "knuckles:sharp"], "stomach":["abs:gut", "noabs:liquor"] }] }'; my $decoded = decode_json($test); my @layer1 = @{ $decoded->{'body'} }; foreach ( @layer1 ) { my @layer2 = $_->{$decoded->{'arms'} }; foreach( @layer2 ) { print $_->{$decoded->{'hands'}} . " "; } } Now, at least the code will compile under u

Categories : Perl

Perl: Why do i need to set the latin1 flag explicitly since JSON 2.xx?
This is such a huge can of worms that you're opening here. I suspect that the answer is something along the lines of "a bug was fixed in the character handling of JSON.pm". But it's hard to know what is going on without a lot more information about your situation. How is $string_with_umlauts being set? How are you encoding the data that you write to the HTML document? Do you want to handle utf8 data correctly (you really should) or are you happy assuming that you live in a Latin1 world? It's important to realise that if you completely ignore Unicode considerations then it can often seem that your programs are working correctly as errors often cancel each other out. When you start to address Unicode issues, it can seem that your programs are getting worse until you address all of the is

Categories : Json

Needing to send a JSON request in perl
You perform the request before you have fully populated it! This line does the request: my $res = $ua->request($req); but a few lines later, you fill some fields: $req->header( 'Content-Type' => 'application/json' ); $req->content( $json ); Try swapping that around: my $json = ...; my $ua = LWP::UserAgent->new; my $req = POST 'URL IS HERE'; $req->header( 'Content-Type' => 'application/json' ); $req->content( $json ); my $res = $ua->request($req); Oh, never $res->content. The value of that method is not generally something usable. You always want $res->decoded_content;

Categories : Json

Website Perl Script fails with json module
DVK commented: Also, check if you have JSON or JSON::PP installed (the latter was in the core Perl since 5.14): perl -MJSON -e ''and perl -MJSON::PP -e '' Thanks DVK, if I include use JSON::PP instead of use JSON, the perl script works. I had to change some JSON-specific functions to JSON::PP functions (ie. change $json->objToJson to $json->encode) for it to work with JSON::PP. This link also provided some help

Categories : Json

Normalization on utf8 filenames stored in JSON with perl
Even though it may be important right now only to convert a few file names to the same normalization for comparison, other unexpected problems could arise from almost anywhere if JSON data has a different normalization. So my suggestion is to normalize the entire input from both sources as your first step before doing any parsing (i.e., at the same time you read the file and before decode_json). This should not corrupt any of your JSON structures since those are delimited using ASCII characters. Then your existing perl code should be able to blindly assume all UTF8 characters have the same normalization. $rawdata1 = read_file($file1, {binmode => ':raw'}) or die "..."; $rawdata2 = read_file($file2, {binmode => ':raw'}) or die "..."; my $json1 = decode_json NFD($rawdata1); my $json2

Categories : Json

Remove __CLASS__ From JSON Output of Moose Object In Perl
MooseX::Storage is not particularly suited to this task. It's designed to enable persistent storage of Moose objects (that's why it adds the __CLASS__ field) so they can be retrieved by your program later. If your goal is to construct objects for a JSON API, then it would probably be much easier to just pass your object's hashref directly to JSON.pm. use JSON -convert_blessed_universally; my $json_obj = JSON->new->allow_blessed->convert_blessed; my $jsonString = $json_obj->encode( $componentObject ); The -convert_blessed_universally option (in addition to being a mouthful) will cause JSON.pm to treat blessed references (objects) as ordinary Perl structures which can be translated to JSON directly. EDIT: Looks like you have to add the allow_blessed and convert_blessed opti

Categories : Json

Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'WebApplication.Title via a reference conversion, boxing conversion,
you Cannot convert type 'System.Web.UI.WebControls.ListItem' to your class Title try this Title choosen; private void lb1_SelectedIndexChanged(object sender, EventArgs e) { if (lb1.SelectedIndex == -1) return; choosen.name = lb1.SelectedItem.Text;//set object properties choosen.value= lb1.SelectedItem.Value; } public class Title { //your Title class has some properties so..i assume some properties public string name { get; set; } public string value { get; set; } }

Categories : Asp Net

Conversion between JSON with wrapped structure and pojo with flattended structure
You can try with this algorithm: Read JSON as Map. Flatten map Use ObjectMapper to convert Map into POJO. Implementation could looks like this: ObjectMapper mapper = new ObjectMapper(); Map<String, Map<String, String>> map = mapper.readValue(new File("X:/test.json"), Map.class); Map<String, String> result = new HashMap<String, String>(); for (Entry<String, Map<String, String>> entry : map.entrySet()) { result.putAll(entry.getValue()); } System.out.println(mapper.convertValue(result, MyPojo.class));

Categories : Java

Why implicit conversion is occurring in "if expression" although it should be explicit conversion
That code very much is supposed to compile. The standard expended a very great deal of effort to ensure that it does. There are a number of places where an expression is "contextually converted to bool" In those places, explicit bool conversions will be called if they're available. One of those contextual conversions is the if expression, as in your case. This language allows explicit operator bool types to still be used for conditional checking if(expr), but you can't other things without an explicit conversion. You can't pass it to a function that takes a bool; you can't return it from a function that returns bool, and so forth. All of the contextual conversions are explicit expressions in language features. So explicit operator bool protects you from implicit user-defined conversions

Categories : C++

json format to csv format conversion, special case
Using RJSONIO you can do something like this : library(RJSONIO) tt <- fromJSON(tt) data.frame(business_id =tt$business_id, do.call(rbind,list(tt$checkin_info))) business_id X11.3 X8.5 X15.0 X15.3 X15.5 X14.4 X14.5 X14.6 X14.0 X14.1 X14.3 X0.5 X1.6 X11.5 X11.4 X13.1 X11.6 X11.1 X13.6 X13.5 X11.2 X12.6 X12.4 1 KO9CpaSPOoqm0iCWm5scmg 17 1 2 2 2 1 3 6 2 2 2 1 1 3 11 1 6 18 5 4 9 5 8 X12.5 X12.2 X12.3 X12.0 X12.1 X13.3 X9.5 X9.4 X13.2 X20.1 X9.6 X16.3 X16.1 X16.5 X10.0 X10.1 X10.2 X10.3 X10.4 X10.5 X10.6 X11.0 1 5 12 19 20 14 1 2 1 6 1 4 1 1 1 3 4 4 4 1 2 2 3 EDIT I use a new idea here. It is easi

Categories : Json

Why does conversion to reference interfere with conversion to bool?
This D1 d1a = D1('a', 'a'); D1 d1b = D1('b', 'a'); D2 d2a = D2('a', 'a'); D2 d2b = D2('b', 'a'); if (d1a) std::cout << "d1a "; if (d1b) std::cout << "d1b "; if (d2a) std::cout << "d2a "; if (d2b) std::cout << "d2b "; prints d1a d2a for me. You have if (D2 d2a = D2('a', 'a')) std::cout << "d2a "; if (D2 d2a = D2('b', 'a')) std::cout << "d2b "; What happens if you don't use the same name in both cases? There's only d1a and d2a in the output if I replace the 4th if by if (D2 d2b = D2('b', 'a')) std::cout << "d2b ";

Categories : C++

How to iterate a multidimensional json_decoded object in Perl to create a new json object?
Well, you aren't really going wrong; it is just the JSON format that is being as stupid as possible. The JSON is a hash of keys (which are sorted, numeric strings) which map to another level of hashes, which have the keys name and value: { "0": {"name": "someKey", "value": "someValue"}, "1": {"name": "anotherKey", "value": "anotherValue"} } (This data should probably be encoded as [{"someKey": "someValue"}, {"anotherKey": "anotherValue"}].) So what we'll do is to loop through the numerically sorted keys for the outer hash: for my $index (sort { $a <=> $b } keys %records) { ... } Inside that loop, we do not loop through the keys/values of the hash values. Instead, we just pick the values of the keys name and value: my $record_value = $records{$index}; my ($key, $value)

Categories : PHP

Converting array of numbers to json in perl, getting array of strings
From the JSON documentation: You can force the type to be a number by numifying it: my $x = "3"; # some variable containing a string $x += 0; # numify it, ensuring it will be dumped as a number $x *= 1; # same thing, the choice is yours. I would try something like this: $json = to_json({numbers_array => [map { $_ + 0 } @numbers_array]}); print $json;

Categories : Json

Invalid data conversion: Parameter instance 50.0/100 is invalid for the requested conversion. ERRORCODE=-4461, SQLSTATE=42815
If I had to guess I would say it is an auto conversion issue. You had something like 5 * 50.0 / 100 and it worked. No you have 50.0 / 100 and it fails. It seems in the first it converted all operands to integers and in the second it converts them to floating point. But 100 is not a valid floating point constant. So change your new output to 50.0 / 100.0 or 50 / 100

Categories : SQL

json format to csv format conversion, using R
There must be a more readable solution... The following replaces the NULLs with NAs, calls as.data.frame on each row, and combines the rows with rbind. tmp <- lapply( raw, function(u) lapply(u, function(x) if(is.null(x)) NA else x) ) tmp <- lapply( tmp, as.data.frame ) tmp <- do.call( rbind, tmp ) tmp

Categories : Json

Perl Google Yahoo And etc Engine didn't bring results, Need help perl expert
For one thing, you are using a zero-argument prototype for a function that you pass an argument to. Don't do that. For another, are you inspecting the response whenever you are unhappy with the results? Is the response something other than 200? Does the response include an error message from the search engine? Based on this line alone: &msg("$chan", "$logo(7@2$engine15)12 Total:4 (".scalar(@total).")12 Clean:4 (".scalar(@clean).")"); I also conclude that you're not using use strict and use warnings. Do that.

Categories : Perl

Customize Perl Markdown to recognize note paragraphs with title (newbie to perl)
What you want seems to be: sub _DoNotesAndWarnings { my $text = shift; $text =~ s{ ~([!?]) # $1 = style class (?:s*#([^#]+)#s*)? # $2 = title, optional (.+?) # $3 = Block text ~[!?] # closing syntax }{ my $style = ($1 eq '!') ? "Warning" : "Note"; my $title = $2 || $style; "<div class="$style">" . _RunSpanGamut("<b>$title:</b> " . $3) . "</div> "; }egsx; return $text; }

Categories : Perl



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.