Posts

Showing posts with the label Json

Convert XML To JSON (and Back) Using Javascript

Answer : I think this is the best one: Converting between XML and JSON Be sure to read the accompanying article on the xml.com O'Reilly site, which goes into details of the problems with these conversions, which I think you will find enlightening. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit. https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/): This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries. API functions new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here X2JS.xml2json - Convert XML specified as DOM Object to JSON X2JS.json2xml - Convert JSON to XML DOM Object X2JS.xml_str2json - Convert XML specified as string to JSON X2JS.json2xml_str - Convert JSON to XML s...

Angular: 'Cannot Find A Differ Supporting Object '[object Object]' Of Type 'object'. NgFor Only Supports Binding To Iterables Such As Arrays'

Answer : As the error messages stated, ngFor only supports Iterables such as Array , so you cannot use it for Object . change private extractData(res: Response) { let body = <Afdelingen[]>res.json(); return body || {}; // here you are return an object } to private extractData(res: Response) { let body = <Afdelingen[]>res.json().afdelingen; // return array from json file return body || []; // also return empty array if there is no data } Remember to pipe Observables to async, like *ngFor item of items$ | async , where you are trying to *ngFor item of items$ where items$ is obviously an Observable because you notated it with the $ similar to items$: Observable<IValuePair> , and your assignment may be something like this.items$ = this.someDataService.someMethod<IValuePair>() which returns an Observable of type T. Adding to this... I believe I have used notation like *ngFor item of (items$ | async)?.someProperty You only nee...

Convert Json Table Arrays To Objects With Jq

Answer : Answering my own question: jq 'to_entries|map(.key) as $keys| (map(.value)|transpose) as $values |$values|map([$keys, .] | transpose| map( {(.[0]): .[1]} ) | add)' Explanation: Extract keys ["IdentifierName", "Code"] and values as [ [ "A", 5 ], [ "B", 8 ], [ "C", 19 ] ] Then to index from keys to values, take json-seq of key-tuple with (each) value tuple and transpose and zip them in pairs. echo '[[ "IdentifierName", "Code" ], [ "C", 19 ] ]'|jq '.|transpose| map( {(.[0]): .[1]} ) | add' Combining both gives solution. This will work for any number of elements (0 and 1 are just key and value, not first and second). $ jq '[.IdentifierName, .Code] | transpose | map( { "IdentifierName": .[0], "Code": .[1] } ) ' file.json [ { "IdentifierName": "A", "Code": 5 }, { "IdentifierN...

Convert String To JSON Array

Answer : Here you get JSONObject so change this line: JSONArray jsonArray = new JSONArray(readlocationFeed); with following: JSONObject jsnobject = new JSONObject(readlocationFeed); and after JSONArray jsonArray = jsnobject.getJSONArray("locations"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject explrObject = jsonArray.getJSONObject(i); } Input String [ { "userName": "sandeep", "age": 30 }, { "userName": "vivan", "age": 5 } ] Simple Way to Convert String to JSON public class Test { public static void main(String[] args) throws JSONException { String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}] "; JSONArray jsonArr = new JSONArray(data); for (int i = 0; i < jsonArr.length(); i++) { JSONObject jsonO...

Convert JSONObject To Map

Answer : use Jackson (https://github.com/FasterXML/jackson) from http://json.org/ HashMap<String,Object> result = new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class); You can use Gson() (com.google.gson) library if you find any difficulty using Jackson. HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class); This is what worked for me: public static Map<String, Object> toMap(JSONObject jsonobj) throws JSONException { Map<String, Object> map = new HashMap<String, Object>(); Iterator<String> keys = jsonobj.keys(); while(keys.hasNext()) { String key = keys.next(); Object value = jsonobj.get(key); if (value instanceof JSONArray) { value = toList((JSONArray) value); } else if (value instanceof JSONObject) { value = toMap((JSONObject) value); } map.put(key,...

Can't Import JSON In Excel 2016 Using "Get & Transform" Feature

Answer : I ran into the same situation, and then found a work around on the following page: https://techcommunity.microsoft.com/t5/Get-and-Transform-Data/Missing-JSON-option-at-Data-gt-New-query-gt-From-File/td-p/69747 In short, the steps are to: New Query -> From Other Sources -> From Web; Type in (or Copy-Paste) an url to you Json data and hit OK button; After Query Edit opens, right-click a document icon on a query dashboard and select JSON and your data is transformed to a table data format. Thanks to 'Good Boy' who provided the work around in the article mentioned. If the json file is on your computer, a file, you can enter ' file:\c:\filename.json ' in place of the web url. Don't include the '. The easiest way is to use the file browser and copy the path to the file and then add the file name at the end.

Convert Mongoose Docs To Json

Answer : You may also try mongoosejs's lean() : UserModel.find().lean().exec(function (err, users) { return res.end(JSON.stringify(users)); } Late answer but you can also try this when defining your schema. /** * toJSON implementation */ schema.options.toJSON = { transform: function(doc, ret, options) { ret.id = ret._id; delete ret._id; delete ret.__v; return ret; } }; Note that ret is the JSON'ed object, and it's not an instance of the mongoose model. You'll operate on it right on object hashes, without getters/setters. And then: Model .findById(modelId) .exec(function (dbErr, modelDoc){ if(dbErr) return handleErr(dbErr); return res.send(modelDoc.toJSON(), 200); }); Edit: Feb 2015 Because I didn't provide a solution to the missing toJSON (or toObject) method(s) I will explain the difference between my usage example and OP's usage example. OP: UserModel .find({}) // will get all...

Converting XML To JSON Using Python?

Answer : xmltodict (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this "standard". It is Expat-based, so it's very fast and doesn't need to load the whole XML tree in memory. Once you have that data structure, you can serialize it to JSON: import xmltodict, json o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>') json.dumps(o) # '{"e": {"a": ["text", "text"]}}' There is no "one-to-one" mapping between XML and JSON, so converting one to the other necessarily requires some understanding of what you want to do with the results. That being said, Python's standard library has several modules for parsing XML (including DOM, SAX, and ElementTree). As of Python 2.6, support for converting Python data structures to and from JSON is included in the json module. So the infrastructure is there. You can use the ...

Creating BSON Object From JSON String

Answer : ... And, since 3.0.0, you can: import org.bson.Document; final Document doc = new Document("myKey", "myValue"); final String jsonString = doc.toJson(); final Document doc = Document.parse(jsonString); Official docs: Document.parse(String) Document.toJson() Official MongoDB Java Driver comes with utility methods for parsing JSON to BSON and serializing BSON to JSON. import com.mongodb.DBObject; import com.mongodb.util.JSON; DBObject dbObj = ... ; String json = JSON.serialize( dbObj ); DBObject bson = ( DBObject ) JSON.parse( json ); The driver can be found here: https://mongodb.github.io/mongo-java-driver/ The easiest way seems to be to use a JSON library to parse the JSON strings into a Map and then use the putAll method to put those values into a BSONObject . This answer shows how to use Jackson to parse a JSON string into a Map .

Convert Map To JSON Object In Javascript

Answer : Given in MDN, fromEntries() is available since Node v12: const map1 = new Map([ ['foo', 'bar'], ['baz', 42] ]); const obj = Object.fromEntries(map1); // { foo: 'bar', baz: 42 } For converting object back to map: const map2 = new Map(Object.entries(obj)); // Map(2) { 'foo' => 'bar', 'baz' => 42 } I hope this function is self-explanatory enough. This is what I used to do the job. /* * Turn the map<String, Object> to an Object so it can be converted to JSON */ function mapToObj(inputMap) { let obj = {}; inputMap.forEach(function(value, key){ obj[key] = value }); return obj; } JSON.stringify(returnedObject) You could loop over the map and over the keys and assign the value function createPaths(aliases, propName, path) { aliases.set(propName, path); } var map = new Map(), object = {}; createPaths(map, 'paths.aliases.server.entry', 'src/test'); createPaths(ma...

Convert PHP Date Into Javascript Date Format

Answer : You should probably just use a timestamp $newticket['DateCreated'] = strtotime('now'); Then convert it to a Javascript date // make sure to convert from unix timestamp var now = new Date(dateFromPHP * 1000); Javascript Date class supports ISO 8601 date format so I would recommend: <?php date('c', $yourDateTime); // or for objects $dateTimeObject->format('c'); ?> documentation says that: format character 'c' is ISO 8601 date (added in PHP 5) example: 2004-02-12T15:19:21+00:00 for more information: http://php.net/manual/en/function.date.php It is pretty simple. PHP code: $formatted_date = $newticket['DateCreated'] = date('Y/m/d H:i:s'); Javascript code: var javascript_date = new Date("<?php echo $formatted_date; ?>");

Convert XML To JSON With NodeJS

Answer : I've used xml-js - npm to get the desired result. First of all I've installed xml-js via npm install xml-js Then used the below code to get the output in json format var convert = require('xml-js'); var xml = require('fs').readFileSync('./testscenario.xml', 'utf8'); var result = convert.xml2json(xml, {compact: true, spaces: 4}); console.log(result); You can use xml2json npm for converting your xml in to json. xml2json. Step 1:- Install package in you project npm install xml2json Step 2:- You can use that package and convert your xml to json let xmlParser = require('xml2json'); let xmlString = `<?xml version="1.0" encoding="UTF-8"?> <TestScenario> <TestSuite name="TS_EdgeHome"> <TestCaseName name="tc_Login">dt_EdgeCaseHome,dt_EdgeCaseRoute</TestCaseName> <TestCaseName name="tc_Logout">dt_EdgeCaseRoute</TestCaseName> ...

Convert JSON Array In MySQL To Rows

Answer : It's true that it's not a good idea to denormalize into JSON, but sometimes you need to deal with JSON data, and there's a way to extract a JSON array into rows in a query. The trick is to perform a join on a temporary or inline table of indexes, which gives you a row for each non-null value in a JSON array. I.e., if you have a table with values 0, 1, and 2 that you join to a JSON array “fish” with two entries, then fish[0] matches 0, resulting in one row, and fish1 matches 1, resulting in a second row, but fish[2] is null so it doesn't match the 2 and doesn't produce a row in the join. You need as many numbers in the index table as the max length of any array in your JSON data. It's a bit of a hack, and it's about as painful as the OP's example, but it's very handy. Example (requires MySQL 5.7.8 or later): CREATE TABLE t1 (rec_num INT, jdoc JSON); INSERT INTO t1 VALUES (1, '{"fish": ["red", "blue"]}...